Json.NET - Serializing and Deserializing Data

In this post, I am going to explain the process of converting json data to a .NET object and vice versa using Json.NET. 

We will be using the SerializeObject and DeserializeObject methods in JsonConvert class for doing this. These methods encapsulates all the heavy listing done by JsonSerializer class which is actually doing the conversion under the hood.

In the example given below, I am trying to convert a .NET object into json sting using the SerializeObject method. I have created a class which contains two string properties for Id and Name, created an instance of it and intialized the values.

Serializing Data

To use Json.NET , first you need to install the package via NuGet. I have already wrote a post on that subject earlier and you can refer it here. Then you need to import the namespace Newtonsoft.Json into the program.

After that you can call the SerializeObject in JsonConvert class to do the conversion and the resulting json string is store in jsonOutput.

Syntax

JsonConvert.SerializeObject(T inputclass);

Usage 

String jsonOutput = JsonConvert.SerializeObject(clsInfo);

When we call the SerializeObject method, Json.Net will take the properties name from the class definition to create the keys with the same name is the resulting json. The values for these keys are taken from the values in properties of the instance and that's the json string is formed.

If you look at the class definition closely, you can see that I have specified string as type for both the properties and when the json string is formed, the value is enclosed in the double quotes. Let's change the type of the ColorId property to int and will see how will our json string look like

If you look at the output now, the ColorId property is now not enclosed in double quotes. Json.net will always consider the type of property and based on that only it's building the json string.

Deserializing Data

For deserialization, we will make use of the DeserializeObject  method in JsonConvert class. It expects the json string that need to be converted as well the type to which it needs to be converted. Here also I'm making use of the class with two string properties and the magic happens here in this statement.

Usage

ColorInfo clsInfo = JsonConvert.DeserializeObject<ColorInfo>(jsonOutput);

Syntax

JsonConvert.DeserializeObject<T>(string inputString);

As we done in the case of serialization, let's change the property of the ColorId property to int and see how deserialization goes

You will be surprised that there are no error and conversion happened successfully. That's because Json.net will handle that conversion internally there by producing the desired output.


No Comments

Add a Comment