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.
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:
- public class Employee
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- }
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:
- private void JSONSerilaize()
- {
-
- Employee empObj = new Employee();
- empObj.ID = 1;
- empObj.Name = "Manas";
- empObj.Address = "India";
- empObj.DOB = DateTime.Now;
-
-
- string jsonData = JsonConvert.SerializeObject(empObj);
-
- Response.Write(jsonData);
- }
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:
- string json = @"{
- 'ID': '1',
- 'Name': 'Manas',
- 'Address': 'India'
- }";
Now we will convert it to a .NET object using 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 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
LINQ to JSON
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.
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 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:
- 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 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:
- 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 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.
JSchema:
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:
- 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);
-
- user = JObject.Parse(@"{
- 'name':'manas',
- 'language': ['C', 'C++']
- }");
-
- valid = user.IsValid(schema);
- }
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:
- public class Student
- {
- public int ID { get; set; }
-
- [EmailAddress]
- [JsonProperty("email", Required = Required.Always)]
- public string Email;
- }
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
Conclusion
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.