Asp.Net Serialization & Deserialization with C#.Net

Category > ASP.NET || Published on : Saturday, February 6, 2016 || Views: 12217 || Asp.Net Serialization & Deserialization with C#.Net Serialization Deserialization


Introduction

Here Pawan Kumar will explain how to Asp.Net Serialization & Deserialization with C#.Net

Description

In previous post I have explained Set max length of MultiLine TextBox in ASP.Net, Allow only alphabets in a textbox using javascript in asp.net, jQuery, ASP.NET - How to validate the file type and file size of File Upload control on file selection using the jQuery .Change() event, Create a QR Code with a Logo in ASP.Net C#, jQuery to Check UnCheck All CheckBoxes in Repeater in Asp.Net C#, Check UnCheck All CheckBoxes in Asp.Net GridView using jQuery, and many more articles.

Now I will explain How to Asp.Net Serialization & Deserialization with C#.Net

So follow the steps to learn Asp.Net Serialization & Deserialization with C#.Net

Definition of Serialization

Serialization is the process of taking an object and converting it to a format in which it can be transported across a network or persisted to astorage location. The storage location could be as simple as using a file or a database. The serialized format contains the object's state information. Deserialization is the process of using the serialized state information to reconstruct the object from the serialized state to its original state. In essence, the process of serialization allows an object to be serialized, shipped across the network for remoting or persisted in a storage location such as the ASP.NET cache, and then be reconstructed for use at a later point in time.

Source: http://www.codeguru.com/csharp/csharp/cs_syntax/serialization/article.php/c5821/SerializationDeserialization-in-NET.htm

Why Serialization and Deserialization

Let's say we have a very complex object and we need XML format for our XSLT rendering on HTML page. Then we have one option that we will write a XML file in the disk after parsing object variable and than load the XML file in XmlDocument object. But is it really a good approach? No, of course not. Why so. This is because in large applications, we have so many users and we will be writing files for every one.

This will take lots of space as well as it is risky that might be files are shared among the users or any human being can read that file.So what do we do now? Yes at this time, go with serialization, get an XML string and just load it to XmlDocument. This will be done in code.

This can be implemented with web services. When we have created a proxy of any web service and we need to send and receive response, it is very beneficial.

Source: http://www.codeproject.com/Articles/36781/Serialization-and-Deserialization-in-ASP-NET-with

Serialization is the process of converting the state of an object into a form that can be persisted or transported. The complement of serialization is deserialization, which converts a stream into an object. Together, these processes allow data to be easily stored and transferred.

The .NET Framework features two serializing technologies:

    Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the Clipboard. You can serialize an object to a stream, to a disk, to memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.

    XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is likewise an open standard, which makes it an attractive choice.
Source: Microsoft (https://msdn.microsoft.com/en-us/library/7ay27kt9%28v=vs.110%29.aspx)

Introduction:

Here to explain the process i have created a new project and I have created a class file called Student with the below mentioned properties.

Step 1: Create a new website using Visual Studio 2010 and App_code folder and then add the a new class with name "Student" and write the following codes:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Student
/// </summary>
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FatherName { get; set; }
    public string MotherName { get; set; }

}

 After that add a new aspx(default.aspx) page. In this page add System.Web.Script.Serialization namespace. In this we have to createa new instance of Student Class and assigned some dummy values to the object. After that using JavaScriptSerializer().Serialize() method, Below is the entire code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Student studentObj = new Student();

        studentObj.FirstName = "Steve";
        studentObj.LastName = "Cruz";
        studentObj.FatherName = "Bill";
        studentObj.MotherName = "Merlin";

        // Serialize Student Object
        var json = new JavaScriptSerializer().Serialize(studentObj);
        Response.Write(json.ToString());
    }
}

The sample output will look like below.

For deserialize the serialized data i have created a another aspx page with the below design. And now using JavaScriptSerializer().Deserialize<T>() method i have deserialized the json into employee object and binded the form fields.

Below is the code i used for ASP.NET aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DeSerialization.aspx.cs" Inherits="DeSerialization" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Literal ID="ltlFirstName" runat="server"></asp:Literal><br />

        <asp:Literal ID="ltlLastName" runat="server"></asp:Literal><br />
        <asp:Literal ID="ltlFatherName" runat="server"></asp:Literal><br />
        <asp:Literal ID="ltlMotherName" runat="server"></asp:Literal>


    </div>
    </form>
</body>
</html>

Code Behind:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

public partial class DeSerialization : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var json = "{'FirstName':'Steve','LastName':'Cruz','FatherName':'Bill','MotherName':'Merlin'} ";
        Student studentObj = new Student();
        studentObj = new JavaScriptSerializer().Deserialize<Student>(json);
        if (studentObj != null)
        {
            ltlFirstName.Text = studentObj.FirstName;
            ltlLastName.Text = studentObj.LastName;
            ltlFatherName.Text = studentObj.FatherName;
            ltlMotherName.Text = studentObj.MotherName;
        }
    }
}

Out will be something like below

Conclusion:

So, In this tutorial we have learned, Asp.Net Serialization & Deserialization with C#.Net

Download Source Codes Live Demo