Why JSON is important?

In most of the cases, we use web services to receive and manipulate data. As well as when we use third party APIs’, they generate JSON data. JSON or the JavaScript Object Notation is the easiest way of serializing and sending data over a network. Due to its lightweight nature and high readability, people tend to use JSON over other data formats. A Simple example of how JSON is arranged is given below.

{
     "name": "Steve",
     "age": 30,
     "address": {
         "city": "New York",
         "state": "NY"
     }
}

Implement JSON Serialization and Deserialization in C#

As we know there are several utility classes provided by C# to implement Serialization and Deserialization. Now you might have a doubt that what is Serialization and Deserialization? We will be discussing it shortly and before that, let’s go through the methods used to do the serialization and deserialization in C#. There are mainly 2 ways of doing this.

  • By using JSON.NET library
  • By using JavaScriptJSONSerializer class

We will be discussing all the listed methods above to achieve the serialization and deserialization in C#.

What are Serialization and Deserialization?

In simply Serialization refers to converting a custom .NET object into JSON string format and Deserialization is the opposite of the serialization. When JSON string is transmitted over the network, by using deserialization, it will be converted to a custom object. From the below example, it will be more clear.

As we have discussed earlier, both the methods have their own methods to do the serialization and deserialization. But the primary concept of serialization and deserialization is similar.

Serialization and Deserialization using Newtonsoft.Json Library

This library is not defined by C# itself. This is a third party library which we want to import to our project to do the serialization and deserialization. It’s a popular JSON framework for .NET which can be found on nugget (Also known as JSON.NET). It uses JSONSerializer and converts custom .NET objects into JSON text and also maps JSON text into a particular object in C#. As it is stated in the documentation, JSON.NET is considered to be the most effective way of serializing and deserializing. Continuous support towards JSON schema, validations, and high flexibility, surely helped it be used frequently.

// creating a custom object  
Employee emp = new Employee ()  
{  
    Name = "Steve",  
    Phone = 145678903  
};

Now use JSON.NET library and do the serialization and deserialization.

// Convert Employee object to JSON format (Serialization) 
string jsonString = JsonConvert.SerializeObject(emp);

// Convert JSON text to Employee object (Deserialization) 
Employee empObj = JsonConvert.DeserializeObject< Employee >( jsonString);

Serialization and Deserialization using JavaScriptJSONSerializer

This is a built-in class available in the .NET framework. To use this class, add the assembly System.Web.Extensions.dll to your project references library. Then add the namespace as shown below:

using System.Web.Script.Serialization;

Hence it is similar to the JSON.NET Library, it has its own methods for serialization and deserialization. Following code snippet is used as a class which contains two attributes and by using JavaScriptJSONSerializer, we convert it to JSON string and vice versa.

    class Employee
    {      //  creating a class to perform the serialization and deserialization
        public string Name { get; set; }
        public int Phone { get; set; }
    }

To do the serialization, the library provides a method Serialize() which takes one custom object argument and converts it into JSON string.

        // creating an Employee object  
        Employee emp = new Employee()
        {
            Name = "Steve",  //assigning values to variables
            Phone = "555-111-2222"
        };
		// Use Serialize method to convert the object into JSON  
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();  
        string jsonString = jsSerializer.Serialize(emp);

Similarly, we can map the JSON string into the custom object we created earlier using the Deserialize() method in the library. It takes one parameter; the JSON string and converts it into the object.

        // Use Deserialize() method to convert JSON to Object  
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        Employee empObj = jsSerializer.Deserialize<Employee>(jsonString);

At last, let’s assign the values in the object to variables and print them to see whether the deserialization is successful or not;

string name = empObj.Name; 
int phone = empObj.Phone;
Console.WriteLine(“Name is: ” + name);
Console.WriteLine(“Phone Number is: ” + phone);

Output

Name is: Steve
Phone Number is: 555-111-2222

Related Articles

Overview of dependency injection in C#

How to Use Throw Expressions in C# 7.0

Replace hostname in URL using C#

Last modified: February 19, 2019

Comments

Write a Reply or Comment

Your email address will not be published.