JsonConvert:如何忽略值为特定数字的整数类型

时间:2018-04-09 09:59:12

标签: c# json

有没有办法告诉JsonConvert在具有特定值时忽略整数类型值?我想使用整数类型的minValue而不是0作为默认类型,因为0是有效值。

1 个答案:

答案 0 :(得分:2)

Json.NET会尊重System.ComponentModel.DefaultValue属性,所以你可以这样做:

class TestClass {
    [DefaultValue(int.MinValue)]
    public int Value { get; set; }
}

var ser = JsonConvert.SerializeObject(new TestClass() { Value = int.MinValue}, new JsonSerializerSettings
{
    DefaultValueHandling = DefaultValueHandling.Ignore
});
// serializes to empty object {}
Console.WriteLine(ser);

var ser = JsonConvert.SerializeObject(new TestClass() { Value = 0}, new JsonSerializerSettings
{
    DefaultValueHandling = DefaultValueHandling.Ignore
});
// serializes to {"Value" : 0}
Console.WriteLine(ser);

如果您不想装饰任何东西,可以使用自定义合约解析器:

class IntMinValueContractResolver : DefaultContractResolver {
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
        var prop = base.CreateProperty(member, memberSerialization);
        if (prop.PropertyType == typeof(int)) {
            // for int properties, set default value and ignore it when serializing
            // while populating while deserializing
            prop.DefaultValue = int.MinValue;
            prop.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
        }
        return prop;
    }
}

JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
    ContractResolver = new IntMinValueContractResolver()
};
// serializes to empty object {}
var ser = JsonConvert.SerializeObject(new TestClass() { Value = int.MinValue});