ASP.NET – JSON – Serialization and Deserialization


I was looking around for a simple example which would just do a object serialization to a JSON format, and then deserializing back to the original object. I found few examples on MSDN, but did seem to be too long to try. Here I’ve given a simple code which would make your understanding easy, and simpler.

 

Before going into the code, let us first understand what is JSON, and what is its significance in the modern world of web applications.

 

What is JSON?

 

JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.

 

Okay, I understood a little about JSON. Give me an example!

 






I know an example will get your understanding much better. Below is a simple example of how an object can be expressed in JSON notation. Let’s take a classical example of a Person object, and expressing myself as an object.


{

   “firstName”: “Rakki”,

   “lastName”:”Muthukumar”,

   “department”:”Microsoft PSS”,

   “address”: {

      “addressline1”: “Microsoft India GTSC”,

      “addressline2”: “PSS – DSI”,

      “city”: “Bangalore”,

      “state”: “Karnataka”,

      “country”: “India”,

      “pin”: 560028

   }

   “technologies”: [“IIS”, “ASP.NET”,“JavaScript”,“AJAX”]

}

In the above example, address is another object inside my Person, and technologies is an array or strings.

 

Express this as a simple .NET class, please!

 




Here is a simple example.



public class Address
{
    public string addressline1, addressline2, city, state, country;
    public int pin;
}
 
public class Person
{
    public string firstName, lastName, department;
    public Address address = new Address();
    public string[] technologies;
}

I get it. Now what? JSON Serialization / Deserialization?

 





I’m sure you do not want me to write what is serialization, and deserialization here. I’ll touch upon how to use System.Web.Script.Serialization.JavaScriptSerializer to convert an existing object into a JSON string.



JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = “Rakki”;
p1.lastName = “Muthukumar”;
p1.department = “Microsoft PSS”;
p1.address.addressline1 = “Microsoft India GTSC”;
p1.address.addressline2 = “PSS – DSI”;
p1.address.city = “Bangalore”;
p1.address.state = “Karnataka”;
p1.address.country = “India”;
p1.address.pin = 560028;
p1.technologies = new string[] { “IIS”, “ASP.NET”, “JavaScript”, “AJAX” };
 
string str = js.Serialize(p1);

Above code just creates a Person object, and assign some values. Look at the last line where we are actually doing a serialization – means dumping the contents of the object to a JSON notation. Below is the string produced by the above code:



{“firstName”:”Rakki”,”lastName”:”Muthukumar”,”department”:”Microsoft PSS”,”address”:{“addressline1″:”Microsoft India GTSC”,”addressline2″:”PSS – DSI”,”city”:”Bangalore”,”state”:”Karnataka”,”country”:”India”,”pin”:560028},”technologies”:[“IIS”,”ASP.NET”,”JavaScript”,”AJAX”]}


It is the same as how we defined the object before – but in a single line. Now, you have successfully converted your object into a JSON string.


Now how do I deserialize it?

 


Before going into how to deserialize it, let’s just understand when you might want to deserialize the object. Classical example is a JSON object returned from a web service, or from your client side javascript code, and you will be able to deserialize it in the server side to use the received object. 



Person p2 = js.Deserialize<Person>(str);
Response.Write(p2.lastName);

p2.lastName would contain “Muthukumar” if your deserialization works fine. I suggest you to use the Deserialize<T> method since it will reduce the type casting you might be doing if you use DeserializeObject() method which returns a System.Object.


Hope this helps!

Comments (16)

  1. srilakshmi says:

    thanks for giving this article, it helps me a lot.

  2. Shabana says:

    Wonderful and very simple explanation for people who don’t know what JSON is. I am one among them……If there is rating then my 5 goes to it…

  3. Duke says:

    Thanks Rakki for taking the time to post this straight-forward and simple to understand article; I like your style of writing. Keep up the good work!

  4. kamran says:

    Very neat, very simple, very easy to understand and very easy to use. Thank you.

  5. gfsharp says:

    Very nice start to JSON for me! thanks

  6. Satish Patil says:

    this made JSON very simple to understand

  7. Jason Webb says:

    That is great.  Lowered my blood pressure a little bit.

  8. nazia says:

    i have been looking for this stuff from nearly 1 week,it cleared me so many things,keep up the good work n plz upload few more stuff on Ajax….

  9. Jorge Luis says:

    I have been looking for the most basic explanation of JSON and Serialization / Deserialization concept in .NET for hours. Thanks for posting this great introductory article. I am sure it will help many developers to get started on JSON!

  10. Hitesh Agja says:

    Good introductory article. I really enjoy reading this blog post.

  11. Lovepreet says:

    Hi Rakki,

    Your post is very helpful. So far I have been following it to get my JSON file deserialized. But I am kind of stuck on deserializing the array part of the file.

    Below is my file. This is a simplified version of an actual file. I can access the first level objects such as authenticationResultCode, brandLogoUri, etc but not the 'resourceSets' objects. 'resourceSets' is an array of objects. I don't know how to access these objects. Could you please let me know how I can work this out.

    Thanks,

    Lovepreet

    {

    "authenticationResultCode":"ValidCredentials",

    "brandLogoUri":"http://dev.virtualearth.net/Branding

    /logo_powered_by.png",

    "copyright":"Copyright © 2010 Microsoft and its suppliers. All

    rights reserved. This API cannot be accessed and the content and any

    results may not be used, reproduced or transmitted in any manner

    without express written permission from Microsoft

    Corporation.","address":

    {"addressline1":"Microsoft India GTSC","addressline2":"PSS –

    DSI","city":"Bangalore","state":"Karnataka","country":"India","pin":56

    0028},

    "resourceSets":  [    

    {"estimatedTotal":1,

    "resources":{"name":"1 Microsoft Way, Redmond, WA 98052-300",

    "bbox":[47.635884282429323,-122.13737419709076,47.643609717570676,

    -122.12208780290925]},

    "confidence":"High",

    "entityType":"Address"

    ]},

      "statusCode":200,

      "statusDescription":"OK",

      "traceId":"9ff2190c0a88428395c426abaa8cea34"

    }

  12. Sundeep says:

    This explanation was great, and in very simple manner. Thanks

  13. Joe lukas says:

    Very good.  I search around and this was the best article, by far. thanks

  14. Wang Ye says:

    Thank you very much!

  15. Ankit Jain says:

    Very Good Example for the starting. Thanks

  16. Many thanks says:

    it could not be simpler than this. you should write a book for latest web development techniques. I'll be your first customer.