Serialization and Deserialization of JSON Data

Table of Contents
  • What are JSON and JSON Data
  • Serialization and Deserialization
  • Add Reference of namespace
  • Example with code
  • Output

What are JSON and JSON DATA?

 
JavaScript Object Notation (JSON) is an open and text-based data exchange format. In other words, it is a text format for the serialization of structured data. JSON enables the fast exchange of small amounts of data between client browsers and AJAX-enabled Web Services. For more about JSON Data go through the following link:
 
Data Types in JSON
 

Serialization and Deserialization

 
Serialization is a process of converting an object into a stream of bytes. Deserialization is the opposite of serialization, in other words, deserialization is a process of creating an object from a stream of bytes. In the serialization process, the fields or properties of an object, the name of the class and the assembly that contains the class are converted to a stream of bytes. In the process of deserialization, that stream of bytes is deserialized and an exact clone of the original object is created.
 
Serialization-and-Deserialization.jpg
 
Serialization can transmit data to memory/database/file. The main purpose of Serialization is to save the state of an object in order to be able to create it when needed. We can send the object to a web service, can pass an object from one domain to another domain, can pass the object through a firewall as an XML string so security can be maintained or user-specific information can be sent across applications using serialization. 
 
Serialization-and-Deserialization1.jpg
 

Add Reference of namespace

 
We use the DataContractJsonSerializer class to serialize a type instance to a JSON string and deserialize the JSON string to a type instance. The DataContractJsonSerializer class exists under the System.Runtime.Serialization.Json namespace. This namespace is included in the System.Runtime.Serialization namespace in .Net framework 4.0 so we need to add a reference for that namespace.
 
Procedure to add the reference of the namespace to the project:
  1. Right-click on the project
  2. Click on the "Add References" menu item.
      
    Image3.jpg
     
  3. Click on ".NET" and select the "System.Runtime.Serialization" namespace thereafter click on the "OK" button.
     
    Image4.jpg
     
Example with code
 
Create Student Object as a DataContract
 
We create a Student class that has two properties, Name and Address. These two data members will be serialized with the class Student that defined the DataContract.
using System.Runtime.Serialization;
  1. namespace JSONExample  
  2. {  
  3.     [DataContract]  
  4.     public class Student  
  5.     {  
  6.         private string name = string.Empty;  
  7.         private string address = string.Empty;         
  8.    
  9.         [DataMember]  
  10.         public string Name  
  11.         {  
  12.             set  
  13.             {  
  14.                 name = value;  
  15.             }  
  16.             get  
  17.             {  
  18.                 return name;  
  19.             }  
  20.         }  
  21.         [DataMember]  
  22.         public string Address  
  23.         {  
  24.             set  
  25.             {  
  26.                 address = value;  
  27.             }  
  28.             get  
  29.             {  
  30.                 return address;  
  31.             }  
  32.         }  
  33.     }  
Create UI Design
 
We are going to create the following UI Form using CSS:
 
Image5.jpg
 
Create the CSS class for the Form Design as in the following: 
  1. <style type="text/css">  
  2.     .labelContainer  
  3.     {  
  4.         padding-top: 2px;   
  5.         float: left;  
  6.         min-width: 155px;  
  7.     }  
  8.     .valueContainer  
  9.     {   
  10.         float: left;  
  11.     }  
  12.     .clearStyle  
  13.     {  
  14.         clear: both;  
  15.     }  
  16. </style> 
Now create a form to get the student name and address:
  1. <div>  
  2.         <div class="labelContainer">Name </div>  
  3.         <div class="valueContainer">  
  4.             <asp:TextBox ID="txtName" runat="server"></asp:TextBox>  
  5.         </div>  
  6.    
  7.         <div class="clearStyle"></div>  
  8.    
  9.        <div class="labelContainer"> Address</div>  
  10.        <div class="valueContainer">  
  11.         <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>  
  12.        </div>  
  13.    
  14.        <div class="clearStyle"></div>  
  15.    
  16.        <div class="valueContainer">  
  17.         <asp:Button ID="btnSerialization" runat="server" Text="Serialize"  
  18.             onclick="btnSerialization_Click" />  
  19.         </div>  
  20.    
  21.         <div class="clearStyle"></div>  
  22.    
  23.         <div class="labelContainer">Serilaize Data</div>  
  24.         <div class="valueContainer">  
  25.          <asp:Label ID="lblSerilaize" runat="server"></asp:Label>  
  26.         </div>  
  27.    
  28.         <div class="clearStyle"></div>  
  29.    
  30.         <div class="valueContainer">  
  31.             <asp:Button ID="btnDeserialization" runat="server" Text="Deserialize"  
  32.             onclick="btnDeserialization_Click" />  
  33.         </div>  
  34.         <div class="clearStyle"></div>  
  35.    
  36.        <div class="labelContainer"> Object Data </div>  
  37.         <div class="valueContainer">  
  38.             <asp:Label ID="lblDeserialize" runat="server"></asp:Label>  
  39.         </div>  
  40.     </div>
In the above design, we have two buttons, one to serialize data and another to deserialize.
 
Add the following namespace to the .aspx.cs page:
  1. using System;  
  2. using System.IO;  
  3. using System.Runtime.Serialization.Json;  
  4. using System.Text; 
Create a Serialize Method
  1. private void JSONSerialize(Student objStudent)  
  2.        {  
  3.            MemoryStream stream = new MemoryStream();  
  4.            DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Student));  
  5.            jsonSer.WriteObject(stream, objStudent);  
  6.            stream.Position = 0;  
  7.            StreamReader sr = new StreamReader(stream);  
  8.            lblSerilaize.Text = sr.ReadToEnd();  
  9.        } 
Create a Deserialize Method
  1. private void JSONDesrilize(string JSONdata)  
  2.         {             
  3.             DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Student));  
  4.             MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(JSONdata));  
  5.             Student objStudent = (Student)jsonSer.ReadObject(stream);  
  6.             lblDeserialize.Text = string.Format("Name = {0} and Address = {1}", objStudent.Name, objStudent.Address);  
  7.         } 
The entire code of the .aspx.cs page for serializizing and deserializing is:
  1. using System;  
  2. using System.IO;  
  3. using System.Runtime.Serialization.Json;  
  4. using System.Text;  
  5.    
  6. namespace JSONExample  
  7. {  
  8.     public partial class JSONSerializeDeSerialize : System.Web.UI.Page  
  9.     {  
  10.         protected void Page_Load(object sender, EventArgs e)  
  11.         {  
  12.    
  13.         }  
  14.    
  15.         private void JSONSerialize(Student objStudent)  
  16.         {  
  17.             MemoryStream stream = new MemoryStream();  
  18.             DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Student));  
  19.             jsonSer.WriteObject(stream, objStudent);  
  20.             stream.Position = 0;  
  21.             StreamReader sr = new StreamReader(stream);  
  22.             lblSerilaize.Text = sr.ReadToEnd();  
  23.         }  
  24.    
  25.         private void JSONDesrilize(string JSONdata)  
  26.         {             
  27.             DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Student));  
  28.             MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(JSONdata));  
  29.             Student objStudent = (Student)jsonSer.ReadObject(stream);  
  30.             lblDeserialize.Text = string.Format("Name = {0} and Address = {1}", objStudent.Name, objStudent.Address);  
  31.         }  
  32.         
  33.    
  34.         protected void btnSerialization_Click(object sender, EventArgs e)  
  35.         {  
  36.             Student objStudent = new Student();  
  37.             objStudent.Name = txtName.Text;  
  38.             objStudent.Address = txtAddress.Text;  
  39.             this.JSONSerialize(objStudent);  
  40.         }  
  41.    
  42.         protected void btnDeserialization_Click(object sender, EventArgs e)  
  43.         {  
  44.             string jsonData = lblSerilaize.Text;  
  45.             this.JSONDesrilize(jsonData);  
  46.         }  
  47.     }  
OUTPUT
 
 
Image6.jpg


Similar Articles