JSON Serialization and Deserialization in C#

NOTE: Here is the latest article and source code on this topic in C# 12:  How do I serialize and deserialize JSON data in C#

Serialization and Deserialization in .NET

JSON data is a common format these days when passing data between applications. When building a .NET application, JSON data format conversion to .NET objects and vice versa is very common. Serialization is the process of converting .NET objects, such as strings, into a JSON format, and deserialization is the process of converting JSON data into .NET objects. In this article and code examples, we will first learn how to serialize JSON in C# and then how to deserialize JSON in C#. 

What is JSON?

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

serialize and deserialize JSON in C#

JSON supports the following two data structures,

  • Collection of name/value pairs - Different programming languages support this Data Structure.
  • Ordered list of values - includes an array, list, vector or sequence, etc. 

JSON has the 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,
    var user = {"name":"Manas","gender":"Male","birthday":"1987-8-8"}  
  2. Array
    Value order set. An array begins with "[" and ends with "]." And values are separated with commas. For example,
    var userlist = [{"user":{"name":"Manas","gender":"Male","birthday":"1987-8-8"}},    
    {"user":{"name":"Mohapatra","Male":"Female","birthday":"1987-7-7"}}]    
  3. String 
    Any quantity of Unicode character assembly is enclosed with quotation marks. It uses backslash to escape.
    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. Using the class, we can serialize an object into JSON data and deserialize JSON data into an object. It is present in the namespace System.Runtime.Serialization.Json which is available in the assembly System.Runtime.Serialization.dll.

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

Let's create a custom class BlogSite for serialization and deserialization,

[DataContract]  
class BlogSite  
{  
    [DataMember]  
    public string Name { get; set; }  
  
    [DataMember]  
    public string Description { get; set; }  
}

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 creating an instance of MemoryStream class to write an object(BlogSite). Lastly, it creates an instance of StreamReader class to read JSON data from the MemorySteam object.

BlogSite bsObj = new BlogSite()  
{  
    Name = "C-sharpcorner",  
    Description = "Share Knowledge"  
};  
  
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(BlogSite));  
MemoryStream msObj = new MemoryStream();  
js.WriteObject(msObj, bsObj);  
msObj.Position = 0;  
StreamReader sr = new StreamReader(msObj);  
  
// "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}"  
string json = sr.ReadToEnd();  
  
sr.Close();  
msObj.Close(); 

Deserialization

In Deserialization, it does the opposite of Serialization, which converts JSON string to a custom .Net object. The following code creates an instance of the 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 an object(BlogSite). Lastly, it creates an instance of StreamReader class to read JSON data from the MemorySteam object.   

string json = "{\"Description\":\"Share Knowledge\",\"Name\":\"C-sharpcorner\"}";  
  
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))  
{  
   // Deserialization from JSON  
   DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BlogSite));  
   BlogSite bsObj2 = (BlogSite)deserializer.ReadObject(ms);  
   Response.Write("Name: " + bsObj2.Name); // Name: C-sharpcorner
   Response.Write("Description: " + bsObj2.Description); // Description: Share Knowledge  
}

Using JavaScriptJsonSerializer

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

The following code, a snippet, is to declare a custom class of BlogSites type.

class BlogSites  
{  
    public string Name { get; set; }  
    public string Description { get; set; }  
}

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 the object(BlogSites). It returns JSON data in string format.

// Creating BlogSites object  
BlogSites bsObj = new BlogSites()  
{  
   Name = "C-sharpcorner",  
   Description = "Share Knowledge"  
};  
  
// Serializing object to json data  
JavaScriptSerializer js = new JavaScriptSerializer();  
string jsonData = js.Serialize(bsObj); // {"Name":"C-sharpcorner","Description":"Share Knowledge"}  

Deserialization

The following code creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data. In Deserialization, it does the opposite of Serialization, which converts JSON string to a custom .Net object.

// Deserializing json data to object  
JavaScriptSerializer js = new JavaScriptSerializer();  
BlogSites blogObject = js.Deserialize<BlogSites>(jsonData);  
string name = blogObject.Name;  
string description = blogObject.Description;  
  
// Other way to whithout help of BlogSites class  
dynamic blogObject = js.Deserialize<dynamic>(jsonData);  
string name = blogObject["Name"];  
string description = blogObject["Description"];  

Using Json.NET

Json.NET is a third-party library that helps conversion between JSON text and .NET objects 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 Manager -> 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 Manager 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 the static method SerializeObject() of JsonConvert class by passing the object(BlogSites). It returns JSON data in string format.

// Creating BlogSites object  
BlogSites bsObj = new BlogSites()  
{  
    Name = "C-sharpcorner",  
    Description = "Share Knowledge"  
};  
  
// Convert BlogSites object to JOSN string format  
string jsonData = JsonConvert.SerializeObject(bsObj);  
  
Response.Write(jsonData);  

Deserialization

In Deserialization, it does the opposite of Serialization, which converts JSON string to a custom .Net object. The following code calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

string json = @"{  
  'Name': 'C-sharpcorner',  
  'Description': 'Share Knowledge'  
}";  
BlogSites bsObj = JsonConvert.DeserializeObject<BlogSites>(json);    
Response.Write(bsObj.Name); 

For more on JSON.NET, visit here

Conclusion

This article discussed 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.


Recommended Free Ebook
Similar Articles