Sunday, 29 January 2012

C# How To: JSON Serialisation and Deserialisation

I've started to make an active effort in using JSON over XML, the main reason being that I find JSON formatted data to be easier on the eye than XML formatted data. I found a project in our source control repository at work that used JSON formatted data as input. The project used a neat little JSON library that I'll now be using whenever required. The library is called Json.NET. The following code shows how easy it is to serialise a .NET POCO into JSON, and then reconstruct the object back from JSON using the aforementioned library.

Imagine we have a simple class that models a person:

internal class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
We can create an instance of this class and then serialize the object into a JSON string using the JsonConvert class as follows:

var inputPerson = new Person() 
    { FirstName = "Alan", LastName = "Turing", Age = 41 };

string json = JsonConvert.SerializeObject(inputPerson);
The json string variable now contains the value:

{"FirstName":"Alan","LastName":"Turing","Age":41}

Reconstructing the object back from a JSON string is as simple as:

var outputPerson = JsonConvert.DeserializeObject<Person>(json);