Blog

Serialize and Deserialize JSON

I was recently tasked with building a web service that integrates with a 3rd party service in order to get new Contacts into a CRM organization.  This web service utilized the popular JSON, which is a data interchange format, and widely used within many web applications and web services.   More programmers are opting to use JSON over other formats such as XML due to its efficiency and human readability.

When working with JSON or XML, it is important to understand the process of serialization and deserialization.  Serialization is the process of converting data objects into a format of your choice, such as JSON.
Deserialization is the process of converting the serialized data back into a data object for the program to easily read the values of each data member.

The process of serialization occurs within the source application once it’s ready to send to the target application while deserialization will occur within the target application once the data has been received.  There are many frameworks and classes available to serialize and deserialize JSON.

One framework we recommend is Json.NET (http://james.newtonking.com/json) .  It’s a free, open source software, and is noted for its high performance and ease of use over other classes such as DataContractJsonSerializer and JavaScriptSerializer.
In order to start using this framework, you will first need to install the NuGet Visual Studio extension (http://www.nuget.org/). Once installed, open your project in Solution Explorer.  Right click on your project and select Manage NuGet Packages.  Search for Json.NET and click Install.  This will add the Newtonsoft.Json package with the NewtonSoft.Json.dll reference to your project.

Let’s see how the code works.

In the following example, I have set up a class for a data object called Contact:

newtonblogimg1

After creating a Contact object with some sample data, serializing it to JSON will then require only one line of code:

newtonblogimg2
The json result will look like this:

newtonblogimg3

The result can then be deserialized back to an object also using one line of code:

newtonblogimg4
For retrieving values from a specific data member, such as name, you would use the following:

newtonblogimg5

As you can see, there isn’t much coding involved using the JSON.net framework!  It’s clean and simple.  If you have any questions about this topic, feel free to contact Beringer today.