JSON Serialization And Deserialization Using JSON.NET Library In C#

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.
What is Json.NET
Json.NET is a third party library which helps conversion between JSON text and .NET object is 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 purpose.
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 how to install and implement in ASP.NET.
How to install
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:

In Visual Studio, Tools menu -> Manage Nuget Package Manger Solution and type “JSON.NET” to search it online. Here's the figure:
                                                                   Figure 1: Json.NET library installation
In this article we will discuss about the following features:
  • Json Serilization
  • JSON Deserilaization
  • LINQ to JSON
  • Validate JSON
  • Generate Schema 
JSON Serialization
It converts a .NET object to JSON format text. For instance, there is an employee object holding data and we need to convert the object to JSON format. To demonstrate JSON serialization, we will create an Employee class with ID, Name and Address properties. We will utilize this class in coming sections of this article. Here's the code: 
  1. public class Employee  
  2. {  
  3.     public int ID { getset; }  
  4.     public string Name { getset; }  
  5.     public string Address { getset; }  
  6. }  
Now create an object of Employee class and assign required value to its properties. Then call SerializeObject() of JsonConvert class with passing Employee object – it returns JSON format text. Here is the code: 
  1. private void JSONSerilaize()  
  2. {  
  3.     // Serializaion  
  4.     Employee empObj = new Employee();  
  5.     empObj.ID = 1;  
  6.     empObj.Name = "Manas";  
  7.     empObj.Address = "India";  
  8.     empObj.DOB = DateTime.Now;  
  10.     // Convert Employee object to JOSN string format   
  11.     string jsonData = JsonConvert.SerializeObject(empObj);  
  13.     Response.Write(jsonData);  
  14. }  
The following figure is showing the result after generating JSON text from .NET object.
                     Figure 2: Serialization of .NET object to JSON string
JSON Deserialization
It is a reverse process of Json Serialization which we discussed in previous section. Means it converts JSON format text to .NET objects. For instance, we have a string value in JSON format text that holds information about an employee. Now we want to convert that JSON text to a .NET employee object which will map all properties of employee object.
For demonstrating deserialization we have JSON format data:
  1. string json = @"{  
  2.     'ID''1',  
  3.     'Name''Manas',  
  4.     'Address''India'  
  5. }";  
Now we will convert it to a .NET object using DeserializeObject() method of JsonConvert class. Here is the code: 
  1. private void JSONDeserilaize()  
  2. {  
  3.     string json = @"{  
  4.         'ID''1',  
  5.         'Name''Manas',  
  6.         'Address''India'  
  7.     }";  
  9.     Employee empObj = JsonConvert.DeserializeObject<Employee>(json);  
  11.     Response.Write(empObj.Name);  
  12. }  
The following is showing properties of .NET after deserialization from JSON data.
                             Figure 3: Deserialization JSON string
Before staring next features (Linq to Json, Schema validation, Schema Validation etc.), we must install JSON Schema library (Newton.Json.Schema). Use the following command to install Schema library (follow Figure 1).

Install-Package Newtonsoft.Json.Schema

It is designed to parse JSON data and querying over it like LINQ. For instance, a Student knows multiple languages and we want to fetch only languages that contain character “C” (it is discussed below). Here LINQ to JSON plays vital role to accomplish this. It also helps to create JSON Objects.
Before going into examples we will discuss some JSON Classes which will be used further.

It represents a JSON Object. It helps to parse JSON data and apply querying (LINQ) to filter out required data. It is presented in Newtonsoft.Json.Linq namespace.

It represents a JSON Array. We can add elements to JArray object and convert into JSON string. It presents in Newtonsoft.Json.Linq namespace. Following code snippet defines how to add values to JArray object:
  1. JArray array = new JArray();  
  2. array.Add("Manual text");  
  3. array.Add(new DateTime(2000, 5, 23));  

It represents an abstract JSON Token. It is a base class of JObject, JArray, JProperty, JValue etc. We can add elements to JArray object and convert into JSON string. It presents in Newtonsoft.Json.Linq namespace.
In the following example we have student information in JSON format. And target is to fetch all languages that contains character “C”. Here's the code:
  1. private void LINQtoJSON()  
  2. {  
  3.     string data = @"{  
  4.        'Name''Manas',  
  5.        'Languages': [  
  6.          'C',  
  7.          'C++',  
  8.          'PHP',  
  9.          'Java',  
  10.          'C#'  
  11.        ]  
  12.      }";

  13.     JObject studentObj = JObject.Parse(data);  
  15.     string name = (string)studentObj["Name"]; // Manas
  16.     string firstLanguage = (string)studentObj["Languages"][0]; // C
  17.     // Fetch all languages which contains character C
  18.     List<string> allLangs = studentObj["Languages"]
  19.                             .Where(temp => temp.ToString().Contains("C"))
  20.                             .Select(t => (string)t).ToList();  // C, C++, C#
  22.     // Creating JArray object and adding elements to it.
  23.     JArray array = new JArray();  
  24.     array.Add("Manual text");  
  25.     array.Add(new DateTime(2000, 5, 23));  
  27.     JObject o = new JObject();  
  28.     o["MyArray"] = array;  
  30.     string json = o.ToString();  
  31. }  
Validate JSON
It is another important functionality of Json.NET library. It helps to define structure of JSON and type (string, array etc.) of each element. Then it needs to validate with original JSON data.

It is in-memory representation of JSON schema. It is present in Newtonsoft.Json.Schema namespace.

In the following example we are creating a schema object with all rules using JSchema class. And we have JSON data which is parsed using JObject. Then IsValid() of JObject class checks whether JSON string is valid or not. It returns Boolean value True or False.
In the following example we are creating:
  1. private void ValidateJSON()  
  2. {  
  3.     JSchema schema = JSchema.Parse(@"{  
  4.       'type''object',  
  5.       'properties': {  
  6.         'name': {'type':'string'},  
  7.         'language': {'type''array'}  
  8.       }  
  9.     }");  
  11.     JObject user = JObject.Parse(@"{  
  12.         'name':null,                
  13.         'language''manas'  
  14.     }");  
  16.     bool valid = user.IsValid(schema); // False  
  18.     user = JObject.Parse(@"{  
  19.         'name':'manas',                
  20.         'language': ['C''C++']  
  21.     }");  
  23.     valid = user.IsValid(schema); // True  
  24. }  
Generate Schema
In this feature we can generate JSON schema from custom objects. For instance, there is a Student class with two properties ID and Email. ID is of integer type, Email is of string type and Email is required. Now we will generate schema based on our rules. Here's the code for Student class:
  1. public class Student  
  2. {  
  3.      public int ID { getset; }  
  5.      [EmailAddress]  
  6.      [JsonProperty("email", Required = Required.Always)]  
  7.      public string Email;      
  8. }  
In the following code we are creating object of JSchemaGenerator class and calls Generate() with passing Student type object. It returns JSchema object type.
                                                   Figure 4: Generate schema for JSON data
In this article we discussed what is Json.NET, how it is helpful to serialize and deserialize an object in ASP.NET. And also we discussed what are the advantages of Json.NET as compared to built-in namespace.
Lastly, from the above discussion we came to know Json.NET is elegant and easy to use. So use it whenever it needs serialize and deserialize an object to JSON.

Up Next
    Ebook Download
    View all
    View all