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.
“addressline1”: “Microsoft India GTSC”,
“addressline2”: “PSS - DSI”,
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?
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;
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:
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?
Person p2 = js.Deserialize<Person>(str);
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!