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 fast exchange of small amounts of data between client bowsers 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;

 

namespace JSONExample

{

    [DataContract]

    public class Student

    {

        private string name = string.Empty;

        private string address = string.Empty;       

 

        [DataMember]

        public string Name

        {

            set

            {

                name = value;

            }

            get

            {

                return name;

            }

        }

        [DataMember]

        public string Address

        {

            set

            {

                address = value;

            }

            get

            {

                return address;

            }

        }

    }

}

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:
 

<style type="text/css">

    .labelContainer

    {

        padding-top: 2px

        float: left;

        min-width: 155px;

    }

    .valueContainer

    { 

        float: left;

    }

    .clearStyle

    {

        clear: both;

    }

</style>


Now create a form to get the student name and address:
 

<div>

        <div class="labelContainer">Name </div>

        <div class="valueContainer">

            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

        </div>

 

        <div class="clearStyle"></div>

 

       <div class="labelContainer"> Address</div>

       <div class="valueContainer">

        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>

       </div>

 

       <div class="clearStyle"></div>

 

       <div class="valueContainer">

        <asp:Button ID="btnSerialization" runat="server" Text="Serialize"

            onclick="btnSerialization_Click" />

        </div>

 

        <div class="clearStyle"></div>

 

        <div class="labelContainer">Serilaize Data</div>

        <div class="valueContainer">

         <asp:Label ID="lblSerilaize" runat="server"></asp:Label>

        </div>

 

        <div class="clearStyle"></div>

 

        <div class="valueContainer">

            <asp:Button ID="btnDeserialization" runat="server" Text="Deserialize"

            onclick="btnDeserialization_Click" />

        </div>

        <div class="clearStyle"></div>

 

       <div class="labelContainer"> Object Data </div>

        <div class="valueContainer">

            <asp:Label ID="lblDeserialize" runat="server"></asp:Label>

        </div>

    </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:
 

using System;

using System.IO;

using System.Runtime.Serialization.Json;

using System.Text;

Create Serialize Method

 

  private void JSONSerialize(Student objStudent)

        {

            MemoryStream stream = new MemoryStream();

            DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Student));

            jsonSer.WriteObject(stream, objStudent);

            stream.Position = 0;

            StreamReader sr = new StreamReader(stream);

            lblSerilaize.Text = sr.ReadToEnd();

        }

Create Deserialize Method
 

  private void JSONDesrilize(string JSONdata)

        {           

            DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Student));

            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(JSONdata));

            Student objStudent = (Student)jsonSer.ReadObject(stream);

            lblDeserialize.Text = string.Format("Name = {0} and Address = {1}", objStudent.Name, objStudent.Address);

        }


The entire code of the .aspx.cs page for serializizing and deserializing is:
 

using System;

using System.IO;

using System.Runtime.Serialization.Json;

using System.Text;

 

namespace JSONExample

{

    public partial class JSONSerializeDeSerialize : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        private void JSONSerialize(Student objStudent)

        {

            MemoryStream stream = new MemoryStream();

            DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Student));

            jsonSer.WriteObject(stream, objStudent);

            stream.Position = 0;

            StreamReader sr = new StreamReader(stream);

            lblSerilaize.Text = sr.ReadToEnd();

        }

 

        private void JSONDesrilize(string JSONdata)

        {           

            DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(Student));

            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(JSONdata));

            Student objStudent = (Student)jsonSer.ReadObject(stream);

            lblDeserialize.Text = string.Format("Name = {0} and Address = {1}", objStudent.Name, objStudent.Address);

        }

      

 

        protected void btnSerialization_Click(object sender, EventArgs e)

        {

            Student objStudent = new Student();

            objStudent.Name = txtName.Text;

            objStudent.Address = txtAddress.Text;

            this.JSONSerialize(objStudent);

        }

 

        protected void btnDeserialization_Click(object sender, EventArgs e)

        {

            string jsonData = lblSerilaize.Text;

            this.JSONDesrilize(jsonData);

        }

    }

}

OUTPUT

Image6.jpg

 

Up Next
    Ebook Download
    View all
    Learn
    View all