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

Introduction

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.

What is 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 with how to install and implement in ASP.NET.

How to install Visual Studio?

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 for it online. Here's the figure:

Figure 1- Json.NET library installation

In this article, we will discuss the following features.

  • JSON Serialization
  • JSON Deserialization
  • LINQ to JSON
  • Validate JSON
  • Generate Schema 

JSON Serialization

It converts a .NET object to JSON format text. For instance, an employee object is holding data, and we need to convert the object to JSON format. We will create an Employee class with ID, Name, and Address properties to demonstrate JSON serialization. We will utilize this class in the coming sections of this article. Here's the code,

public class Employee  
{  
    public int ID { get; set; }  
    public string Name { get; set; }  
    public string Address { get; set; }  
}  

Now create an object of the Employee class and assign the required value to its properties. Then call SerializeObject() of JsonConvert class with passing Employee object – it returns JSON format text. Here is the code: 

private void JSONSerilaize()  
{  
    // Serializaion  
    Employee empObj = new Employee();  
    empObj.ID = 1;  
    empObj.Name = "Manas";  
    empObj.Address = "India";  
    empObj.DOB = DateTime.Now;  
  
    // Convert Employee object to JOSN string format   
    string jsonData = JsonConvert.SerializeObject(empObj);  
  
    Response.Write(jsonData);  
}  

The following figure shows the result after generating JSON text from the .NET object.

JSON Serialization

Figure 2- Serialization of .NET object to JSON string

JSON Deserialization

It is a reverse process of Json Serialization, which we discussed in the previous section. This means it converts JSON format text to .NET objects. For instance, we have a string value in JSON format text containing information about an employee. Now we want to convert that JSON text to a .NET employee object which will map all properties of the employee object.

For demonstrating deserialization, we have JSON format data.

string json = @"{  
    'ID': '1',  
    'Name': 'Manas',  
    'Address': 'India'  
}";  

Now we will convert it to a .NET object using the DeserializeObject() method of JsonConvert class. Here is the code,

private void JSONDeserilaize()  
{  
    string json = @"{  
        'ID': '1',  
        'Name': 'Manas',  
        'Address': 'India'  
    }";  
  
    Employee empObj = JsonConvert.DeserializeObject<Employee>(json);  
  
    Response.Write(empObj.Name);  
}  

The following shows the properties of .NET after deserialization from JSON data.

JSON Deserialization

Figure 3- Deserialization JSON string

Before starting the next features (Linq to Json, Schema validation, Schema Validation, etc.), we must install the JSON Schema library (Newton.Json.Schema). Use the following command to install the Schema library (follow Figure 1).

Install-Package Newtonsoft.Json.Schema

LINQ to JSON

For instance, a Student knows multiple languages, and we want to fetch only languages that contain the character “C” (it is discussed below). Here LINQ to JSON plays a vital role in accomplishing this. It is designed to parse JSON data and query over it like LINQ. It also helps to create JSON Objects.

Before going into examples, we will discuss some JSON Classes which will be used further.

JObject

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.

JArray

It represents a JSON Array. We can add elements to the JArray object and convert it into a JSON string. It presents in Newtonsoft.Json.Linq namespace. The following code snippet defines how to add values to the JArray object,

JArray array = new JArray();  
array.Add("Manual text");  
array.Add(new DateTime(2000, 5, 23));  

JToken

It represents an abstract JSON Token. It is a base class of JObject, JArray, JProperty, JValue, etc. We can add elements to the JArray object and convert it into a JSON string. It presents in Newtonsoft.Json.Linq namespace.

In the following example, we have student information in JSON format. And the target is to fetch all languages that contain the character “C”..” here's the code,

private void LINQtoJSON()  
{  
    string data = @"{  
       'Name': 'Manas',  
       'Languages': [  
         'C',  
         'C++',  
         'PHP',  
         'Java',  
         'C#'  
       ]  
     }";

    JObject studentObj = JObject.Parse(data);  
  
    string name = (string)studentObj["Name"]; // Manas
    string firstLanguage = (string)studentObj["Languages"][0]; // C
    // Fetch all languages which contains character C
    List<string> allLangs = studentObj["Languages"]
                            .Where(temp => temp.ToString().Contains("C"))
                            .Select(t => (string)t).ToList();  // C, C++, C#
    
    // Creating JArray object and adding elements to it.
    JArray array = new JArray();  
    array.Add("Manual text");  
    array.Add(new DateTime(2000, 5, 23));  
  
    JObject o = new JObject();  
    o["MyArray"] = array;  
  
    string json = o.ToString();  
}  

Validate JSON

It is another important function of the Json.NET library. It helps to define the structure of JSON and the type (string, array, etc.) of each element. Then it needs to validate with the original JSON data.

JSchema

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

In the following example, we create 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 the JSON string is valid or not. It returns the Boolean value True or False.

In the following example, we are creating,

private void ValidateJSON()  
{  
    JSchema schema = JSchema.Parse(@"{  
      'type': 'object',  
      'properties': {  
        'name': {'type':'string'},  
        'language': {'type': 'array'}  
      }  
    }");  
  
    JObject user = JObject.Parse(@"{  
        'name':null,                
        'language': 'manas'  
    }");  
  
    bool valid = user.IsValid(schema); // False  
  
    user = JObject.Parse(@"{  
        'name':'manas',                
        'language': ['C', 'C++']  
    }");  
  
    valid = user.IsValid(schema); // True  
}  

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 a schema based on our rules. Here's the code for the Student class,

public class Student  
{  
     public int ID { get; set; }  
  
     [EmailAddress]  
     [JsonProperty("email", Required = Required.Always)]  
     public string Email;      
}  

In the following code, we are creating an object of JSchemaGenerator class and calls Generate() with a passing Student type object. It returns the JSchema object type.

Generate schema for JSON data

Figure 4- Generate schema for JSON data

Conclusion

In this article, we discussed Json.NET and how it is helpful to serialize and deserialize an object in ASP.NET. And also discussed the advantages of Json.NET compared to the built-in namespace.

Lastly, we learned from the above discussion that Json.NET is elegant and easy to use. So use it whenever it needs to serialize and deserialize an object to JSON.


Recommended Free Ebook
Similar Articles