Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonConvert: How to ignore Integer types where the value is a specific number

Tags:

json

c#

Is there a way to tell JsonConvert to ignore integer type values when they have a specific value? I want to use the minValue of an Integer Type instead of 0 as the default type because 0 is a valid value.

like image 564
JohnCambell Avatar asked Apr 09 '18 09:04

JohnCambell


People also ask

How to ignore some properties in JSON?

To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.

What is JsonSerializerSettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json. JsonSerializerSettings. Namespace: Newtonsoft.Json.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

Json.NET will respect System.ComponentModel.DefaultValue attribute, so you can do what you want like this:

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);

If you don't want to decorate anything, you can use custom contract resolver:

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});
like image 148
Evk Avatar answered Oct 21 '22 00:10

Evk