Json.NET - Handling Default Values

In the earlier post we have seen that we can use the NullValueHandling property to handle null values during serialization and omit it from the resulting json string.

There is another feature called Default Value Handling, where we can specify a default value for the attribute and instruct Json.Net to use that value during conversion operation when the underlying property is empty.

The NullValueHandling  property is available in the JsonSerializationSettings class and it accepts 4 values.

1. DefaultValueHandling.Ignore

When we set this property, during serialization, if the property names matches the default values of the data type, like Min Value for Date, Null for nullable fields, then those field will be omitted from the resulting string

In the above example, I have specified null value for ColorCode and min value for effective date. So both of them are omitted from the json output string.

If we haven't set it to ignore, then we will the output as shown below.

{"ColorId":1,"ColorName":"Red","EffectiveDate":"0001-01-01T00:00:00","ColorCode":null}

2. DefaultValueHandling.Include

If you want to the output the with the default values then set it to DefaultValueHandling.Include. This is the default value for DefaultValueHandling attribute. So you completly remove that statement itself.

3. DefaultValueHandling.Populate

When we set this one, If a member that is having a default value specified in the class, but is not present in the json, then the resulting string after deserialization will inclue that and will have the default value populated

4. DefaultValueHandling.IgnoreAndPopulate

When we set this one, then during serialization it will ignore those members having values which are equal to the default values of the type. Also during deserialization, default value is set for those having the attribute specified in the model and is missing in input json string.

In this example you can see that while serializing the instance has default values for EffectiveDate and ColorCode. So in the serialized string both of them are omitted. During deserialization, the string doesn't have ColorCode in it , but since we have specified the default value, the property in the converted object has the default value.


No Comments

Add a Comment