我有一个返回大量汽车功能列表的 API……所有这些都是布尔或整数……基本上我只想显示返回真值或整数 >0 的那些。
我正在使用 JSON.net,以便我使用 ShouldSerialize() 属性来确定是否应该根据其值序列化该属性,并且我的代码如下所示:
public class Features
{
public bool ABS { get; set; }
public bool ShouldSerializeABS()
{
// don't serialize the ABS property if ABS is false
return (ABS != false);
}
public bool Immobiliser { get; set; }
public bool ShouldSerializeImmobiliser ()
{
// don't serialize the Immobiliser property if Immobiliser is false
return (Immobiliser != false);
}
public int BHP { get; set; }
public bool ShouldSerializeBHP ()
{
// don't serialize the BHP property if BHP is false
return (BHP != 0);
}
//..... etc
}
这很好用,给了我想要的结果,但是我只是想知道是否有办法重新考虑这个,这样我的类就不会因为所有的 ShouldSerialize() 属性而变得混乱?
我一直在研究http://james.newtonking.com/projects/json/help/index.html?topic=html/ConditionalProperties.htmCopyConditional
上的属性,看起来可能可以用于这样的目的,但是我似乎仍然得到了很多似乎没有重新考虑的代码IContractResolver
IContractResolver
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 (property.DeclaringType == typeof(Features) && property.PropertyName == "ABS")
{
property.ShouldSerialize =
instance =>
{
Features e = (Features)instance;
return e.ABS != false;
};
}
if (property.DeclaringType == typeof(Features) && property.PropertyName == "Immobiliser")
{
property.ShouldSerialize =
instance =>
{
Features e = (Features)instance;
return e.Immobiliser != false;
};
}
return property;
}
}
如果该属性为假,则使用 ShouldSerializeContractResolver 的此方法似乎不会从类中删除该属性...非常感谢您的帮助