Friday, May 20, 2016

Deserialize JSON to C# Object

JSON (JavaScript Object Notation) is a lightweight data-interchange text format.
Due to light weight characteristic, it is now a days heavily used as data interchange medium.
Web services are exposing data in JSON format.

In this example we will look at sample code in C# to consume JSON data and deserialize it in class objects

Suppose one of such web service exposes data in below JSON format - 

[{"StudentNumber":1,"StudentFirstName":"Tom","StudentLastName":"Alter"},{"StudentNumber":2,"StudentFirstName":"Bruce","StudentLastName":"Lee"},{"StudentNumber":3,"StudentFirstName":"Bret","StudentLastName":"Lee"},{"StudentNumber":4,"StudentFirstName":"Mickey","StudentLastName":"Mouse"},{"StudentNumber":5,"StudentFirstName":"Donald","StudentLastName":"Duck"},{"StudentNumber":6,"StudentFirstName":"Vicky","StudentLastName":"Joseph"}]

Following sample will provide you one way of deserializing JSON data to C# objects and help you to understand it.

1. First we create a public class with public properties. These properties correspond to members of JSON. For above sample JSON public class would be -

public class Student
{
public int StudentNumber { get; set; }
public string StudentFirstName { get; set; }
public string StudentSecondName { get; set; }
} 

In sample JSON we can see StudentNumber, StudentFirstName and 
StudentSecondName are repeating so whole data will be stored in collection of type Student.

2. Next we write a method which will store the data to C# objects  - 
private void JSONToCsharp<T>()
{
WebClient wc = new WebClient();
wc.UseDefaultCredentials = true;
var data = wc.DownloadString(JsonUri);
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(data));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<T>));
var result = serializer.ReadObject(ms);
ms.Close();
ms.Dispose();
}

Once this method is executed, result can easily be type casted to Student and we will have a collection of Student,where  Student[0] will correspond to first record in JSON. ie. 
Student[0].StudentNumber will be 1
Student[0].StudentFirstName will be Tom
Student[0].StudentSecondName will be Alter

Lets look at the code in depth - 
Code is quite easy to understand, WebClient provides methods for sending data to and receiving data from a resource identified by a URI.

var data = wc.DownloadString(JsonUri)
This will download the JSON data to data object of type var.

DataContractJsonSerializer class serializes objects to the JSON and deserializes JSON data to objects. 

While calling above JSONToCsharp method, <T> is replaced with class name ie. Student
JSONToCsharp <Student>();

Finally result object will hold complete JSON data in the form of collection of Student
which can later will type casted like 
Student students = (Student)result;

Note - Following namespaces will be required to use WebClient and DataContractJsonSerializer classes.
using System.Net;
using System.Runtime.Serialization.Json;

Please do share your views about the post.

No comments:

Post a Comment