public class ShouldSerializeContractResolver : DefaultContractResolver
{
public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (member.Name == "BorderRadius" && Style.ShouldSerializeBorderRadius())
{
property.PropertyName = "cornerRadius";
property.ShouldSerialize =
instance => { return true; };
}
if (member.Name == "CornerRadius" && Style.ShouldSerializeCornerRadius())
{
property.PropertyName = "cornerRadius";
property.ShouldSerialize =
instance => { return true; };
}
return property;
}
}
public class Style
{
public double CornerRadius { get; set; } = 9.9;
public BorderRadiusObject BorderRadius { get; set; } = new BorderRadiusObject();
public static bool ShouldSerializeCornerRadius()
{
return false;
}
public static bool ShouldSerializeBorderRadius()
{
return true;
}
}
public class BorderRadiusObject
{
public double A { get; set; } = 1;
public double B { get; set; } = 2;
public double C { get; set; } = 3;
public double D { get; set; } = 4;
}
class Program
{
static void Main(string[] args)
{
var memberJson = Newtonsoft.Json.JsonConvert.SerializeObject(new Style(),
new JsonSerializerSettings {ContractResolver = new ShouldSerializeContractResolver()});
Console.WriteLine(memberJson);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…