Serialization and Deserialization in ASP.NET

In simple words, we can say an object conversion in text stream is serialization and text stream conversion in object of a class is called deserialization

Types of Serialization

1) XML

2)Binary

3)Custom

Serialization in .NET allows the programmer to take an instance of an object and convert it into a format that is easily transmittable over the network, or even stored in a database or file system. This object will actually be an instance of a custom type, including any properties or fields you may have set

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 toXmlDocument. This will be done in code.

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 toXmlDocument

How Do We Achieve This

First note that for serialization and deserialization, we need to use System.Xml.Serialization, because we need to use XmlSerialization class which is provided in System.Xml.Serialization.

To understand this, we assume one example of Category and Items. We have two classes. One is Categoryand another is ItemsCategory has CategoryIDCategory Name and Array of Item. While Item hasItem IDItem NameItem Price and Item Quantity in Stock.

public class Category
{
    private int _CatID;
    private string _CatName;
    private Item[] _Item;

    public int CateboryID
    {
        get
        {
            return _CatID;
        }
        set
        {
            _CatID = value;
        }
    }

    public string CategoryName
    {
        get
        {
            return _CatName;
        }
        set
        {
            _CatName = value;
        }
    }

    public Item[] Item
    {
        get
        {
            return _Item;
        }
        set
        {
            _Item = value;
        }
    }
}

public class Item
{
    private int _ItemID;
    private string _ItemName;
    private int _ItemPrice;
    private int _ItemQtyInStock;

    public int ItemID
    {
        get
        {
            return _ItemID;
        }
        set
        {
            _ItemID = value;
        }
    }

    public string ItemName
    {
        get
        {
            return _ItemName;
        }
        set
        {
            _ItemName = value;
        }
    }

    public int ItemPrice
    {
        get
        {
            return _ItemPrice;
        }
        set
        {
            _ItemPrice = value;
        }
    }

    public int ItemQtyInStock
    {
        get
        {
            return _ItemQtyInStock;
        }
        set
        {
            _ItemQtyInStock = value;
        }
    }
}

private void Serialization()
    {
        Category Cat = new Category();
        Cat.CateboryID = 1;
        Cat.CategoryName = "Phone";
        Item[] Itm = new Item[5];
        for (int i = 0; i < 5; i++)
        {
            Itm[i] = new Item();
            Itm[i].ItemID = i;
            Itm[i].ItemPrice = i * 10;
            Itm[i].ItemQtyInStock = i + 10;
            Itm[i].ItemName = " Item Name : " + i.ToString();

        }
        Cat.Item = Itm;
        XmlSerializer ser = new XmlSerializer(Cat.GetType());
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.StringWriter writer = new System.IO.StringWriter(sb);
        ser.Serialize(writer, Cat); 	// Here Classes are converted to XML String. 
				// This can be viewed in SB or writer.
        // Above XML in SB can be loaded in XmlDocument object
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(sb.ToString());
    }

Here Ser is the object of System.Xml.Serialization.XmlSerializer
class. It gets the Type ofCategory class object by Cat.GetType().
ser.Serialize takes two parameters, one is
 string writer like a target object and another is Cat that is
 source object. This converts or Serializes Cat object and stores stream
into a writer object. Now object is converted into XML string and we
 can find that by usingstringbuilder’s object. Like sb.ToString(). This string 
can be loaded in XML document for further traversing.

Let’s have look at Deserialization

In our application, we have Deserialization function which is called by our click event or whenever this is required. In deserialization, we have created one object of Category  class.
protected void DeSerialize(string XmlString)
    {
        Category Cat = new Category();
        XmlDocument doc = new XmlDocument();
        doc.LoadXml (XmlString);
        XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
        XmlSerializer ser = new XmlSerializer(Cat.GetType());
        object obj = ser.Deserialize(reader);
        // Then you just need to cast obj into whatever type it is, e.g.:
        Category myObj = (Category)obj;
        Now Ser
    }

XMLString for DeSerialization

<?xml version="1.0" encoding="utf-16"?>
<Category>
      <CateboryID>1</CateboryID>
      <CategoryName>Phone</CategoryName>
      <Item>
            <Item>
                  <ItemID>0</ItemID>
                  <ItemName> Item Name : 0</ItemName>
                  <ItemPrice>0</ItemPrice>
                  <ItemQtyInStock>10</ItemQtyInStock>
            </Item>
            <Item>
                  <ItemID>1</ItemID>
                  <ItemName> Item Name : 1</ItemName>
                  <ItemPrice>10</ItemPrice>
                  <ItemQtyInStock>11</ItemQtyInStock>
            </Item>
            <Item>
                  <ItemID>2</ItemID>
                  <ItemName> Item Name : 2</ItemName>
                  <ItemPrice>20</ItemPrice>
                  <ItemQtyInStock>12</ItemQtyInStock>
            </Item>
            <Item>
                  <ItemID>3</ItemID>
                  <ItemName> Item Name : 3</ItemName>
                  <ItemPrice>30</ItemPrice>
                  <ItemQtyInStock>13</ItemQtyInStock>
            </Item>
            <Item>
                  <ItemID>4</ItemID>
                  <ItemName> Item Name : 4</ItemName>
                  <ItemPrice>40</ItemPrice>
                  <ItemQtyInStock>14</ItemQtyInStock>
            </Item>
      </Item>
</Category>

In the above code, we are passing one XML string. This will be
converted into a form of object. Here XMLstring is loaded into
 XmlDocument object and then XmlNodeReader is reading from it.
NowXmlSerialize object is created and we let it know the type of
 object by Cat.GetType(). Now Ser object knows that it has to
convert XML into an object of Category Type. Now ser.Deserialize
(reader) takes XML from reader object and converts into an Object.
Later this object is cast into category. If we add this object
into watch and view, we will find that it has created the class
hierarchy.


					
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s