Json.NET - Customizing Serialization Settings

We can control the serialization/deserialization process using JsonSerializer class. Let's explore some of them

Ignore Null Values

In Json.Net we have the option to ignore values. Somtime during conversions, properties can be null and while doing the serilization, Json.Net will include that also in the result string.

In the program we are not passing any data to ColorCode attribute and after serialization it's coming as null in produced string.

So handle this one, I have created a new instance for JsonSerializer and set the NullValueHandling property to NullValueHandling.Ignore. When it's set to ignore, it will omit the property from writing to the string if the value is null. The value of the NullValueHandling attribute is set to NullValueHandling.Include by default and that's why it exists in the string in the earlier example.

Missing Member Validation

During deserialization we can prevent the process from completing if there are any missing members in the json input string. For example in the below example, there is no entry for the ColorName property in the string. But in the class it's decorated with Mandatory attribute. So if you want Json.NET to raise the exception during such scenario, you need to set the MissingMemberHandling property to MissingMemberHandling.Error so that the conversion won't go through successfully.

By default the value MissingMemberHandling is set to MissingMemberHandling.Ignore, so that no exception are thrown even if members are missing

Formatting

This option is used to format the json string created duing deserialization. Normally it's created without any indendation and shows the output in one single line as shown below.


If the string is bit lengthy then it will be difficult to read and will be hard to maintain also. 

To format the output, just set Formatting property in JsonSerializerSettings instance to Formatting.Indented. Unlike the previous example, here I am using an instance JsonSerializerSettings  class to set the formatting property and this instance is passed to the DeserializeObject method.


No Comments

Add a Comment