Exclusive Clothing Sale On Soft & Soothe

Get up to 63% off on our latest collection.

Shop Now

What is JSON and JSON Serialization


What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language independent.



JSON supports the following two data structures,
  • Collection of name/value pairs - This Data Structure is supported by different programming languages.
  • Ordered list of values - It includes array, list, vector or sequence etc. 
JSON has following styles,
  1. Object
    An unordered "name/value" assembly. An object begins with "{" and ends with "}". Behind each "name", there is a colon. And comma is used to separate much "name/value". For example,
    1. var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}   
  1. Array
    Value order set. An array begins with "[" and end with "]". And values are separated with commas. For example,
    1. var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}},    
    2. {"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]    
  1. String
    Any quantity Unicode character assembly which is enclosed with quotation marks. It uses backslash to escape.
    1. var userlist = "{\"ID\":1,\"Name\":\"Manas\",\"Address\":\"India\"}"    
We can implement JSON Serialization/Deserialization in the following three ways:
  • Using JavaScriptSerializer class
  • Using DataContractJsonSerializer class
  • Using JSON.NET library 
Using DataContractJsonSerializer

DataContractJsonSerializer class helps to serialize and deserialize JSON. It is present in namespace System.Runtime.Serialization.Json which is available in assembly System.Runtime.Serialization.dll. Using the class we can serialize an object into JSON data and deserialize JSON data into an object.

Let's say there is Employee class with properties such as name, address and property values also assigned. Now we can convert the Employee class instance to JSON document. This JSON document can be deserialized into the Employee class or another class with an equivalent data contract. The following code snippets demonstrate about serialization and deserialization.

Let's create a custom class BlogSite for serialization and deserialization,
  1. [DataContract]  
  2. class BlogSite  
  3. {  
  4.     [DataMember]  
  5.     public string Name { getset; }  
  6.   
  7.     [DataMember]  
  8.     public string Description { getset; }  
  9. }  
Serialization

In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and create an instance of MemoryStream class to write object(BlogSite). Lastly it creates an instance of StreamReader class to read JSON data from MemorySteam object.
  1. BlogSite bsObj = new BlogSite()  
  2. {  
  3.     Name = "DotnetOffice",  
  4.     Description = "Share Knowledge"  
  5. };  
  6.   
  7. DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));  
  8. MemoryStream msObj = new MemoryStream();  
  9. js.WriteObject(msObj, bsObj);  
  10. msObj.Position = 0;  
  11. StreamReader sr = new StreamReader(msObj);  
  12.   
  13. // "{\"Description\":\"Share Knowledge\",\"Name\":\"DotnetOffice\"}"  
  14. string json = sr.ReadToEnd();  
  15.   
  16. sr.Close();  
  17. msObj.Close();  
Deserialization

In Deserialization, it does the opposite of Serialization, which means it converts JSON string to a custom .Net object. In the following code, it creates an instance of BlogSite class and assigns values to its properties. Then we create an instance of DataContractJsonSerializer class by passing the parameter BlogSite class and creating an instance of MemoryStream class to write object(BlogSite). Lastly it creates an instance of StreamReader class to read JSON data from MemorySteam object.
  1. string json = "{\"Description\":\"Share Knowledge\",\"Name\":\"DotnetOffice\"}";  
  2.   
  3. using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))  
  4. {  
  5.    // Deserialization from JSON  
  6.    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));  
  7.    BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);  
  8.    Response.Write("Name: " + bsObj2.Name); // Name: DotnetOffice
  9.    Response.Write("Description: " + bsObj2.Description); // Description: Share Knowledge  
  10. }  
  11.    
Using JavaScriptJsonSerializer

JavaScriptSerializer is a class which helps to serialize and deserialize JSON. It is present in namespace System.Web.Script.Serialization which is available in assembly System.Web.Extensions.dll. To serialize a .Net object to JSON string use Serialize method. It's possible to deserialize JSON string to .Net object using Deserialize or DeserializeObject methods. Let's see how to implement serialization and deserialization using JavaScriptSerializer.

Following code snippet is to declare custom class of BlogSites type.
  1. class BlogSites  
  2. {  
  3.     public string Name { getset; }  
  4.     public string Description { getset; }  
  5. }  
Serialization

In Serialization, it converts a custom .Net object to a JSON string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then we create an instance of JavaScriptSerializer and call Serialize() method by passing object(BlogSites). It returns JSON data in string format.
  1. // Creating BlogSites object  
  2. BlogSites bsObj = new BlogSites()  
  3. {  
  4.    Name = "DotnetOffice",  
  5.    Description = "Share Knowledge"  
  6. };  
  7.   
  8. // Serializing object to json data  
  9. JavaScriptSerializer js = new JavaScriptSerializer();  
  10. string jsonData = js.Serialize(bsObj); // {"Name":"DotnetOffice","Description":"Share Knowledge"}  
Deserialization

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it creates JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns custom object (BlogSites) from JSON data.
  1. // Deserializing json data to object  
  2. JavaScriptSerializer js = new JavaScriptSerializer();  
  3. BlogSites blogObject = js.Deserialize(jsonData);  
  4. string name = blogObject.Name;  
  5. string description = blogObject.Description;  
  6.   
  7. // Other way to whithout help of BlogSites class  
  8. dynamic blogObject = js.Deserialize(jsonData);  
  9. string name = blogObject["Name"];  
  10. string description = blogObject["Description"];  
Using Json.NET

Json.NET is a third party library which helps conversion between JSON text and .NET object using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open source software and free for commercial purposes.

The following are some awesome features,
  • Flexible JSON serializer for converting between .NET objects and JSON.
  • LINQ to JSON for manually reading and writing JSON.
  • High performance, faster than .NET's built-in JSON serializers.
  • Easy to read JSON.
  • Convert JSON to and from XML.
  • Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone. 
Let’s start learning how to install and implement:

In Visual Studio, go to Tools Menu -> Choose Library Package Manger -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json.

Install-Package Newtonsoft.Json
OR
In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the figure,

Json.NET

Serialization

In Serialization, it converts a custom .Net object to a Json string. In the following code, it creates an instance of BlogSiteclass and assigns some values to its properties. Then it calls static method SerializeObject() of JsonConvert class by passing object(BlogSites). It returns JSON data in string format.
  1. // Creating BlogSites object  
  2. BlogSites bsObj = new BlogSites()  
  3. {  
  4.     Name = "DotnetOffice",  
  5.     Description = "Share Knowledge"  
  6. };  
  7.   
  8. // Convert BlogSites object to JOSN string format  
  9. string jsonData = JsonConvert.SerializeObject(bsObj);  
  10.   
  11. Response.Write(jsonData);  
Deserialization

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom .Net object. In the following code, it calls static method DeserializeObject() of JsonConvert class by passing JSON data. It returns custom object (BlogSites) from JSON data.
  1. string json = @"{  
  2.   'Name''DotnetOffice',  
  3.   'Description''Share Knowledge'  
  4. }";  
  5.  
  6. BlogSites bsObj = JsonConvert.DeserializeObject(json);  
  7.   
  8. Response.Write(bsObj.Name);  
More on JSON.NET, visit here

Conclusion

In this article we discussed about how many ways we can implement serialization/deserialization in C#. However JSON.NET wins over other implementations because it facilitates more functionality of JSON validation, JSON schema, LINQ to JSON etc. So use JSON.NET always.


Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Soft & Soothe

Get up to 63% off on our latest collection.

Shop Now