Serialization and Deserialization in C#

 

Overview: In this article we will understand what is the serialization and deserialization and how to serialize and deserialize the objects and how many types are there in it.

 

Serialization:

Serialization is the process of converting the state of an object into a form that can be persisted or transported (nothing but streams of bytes).

 

The Microsoft .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.

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.

 

Why would you want to use serialization?

 

There are lots of reasons to serialize the object or xml but the two most important reasons are to persist the state of an object to a storage medium so an exact copy can be re-created at a later stage, and to send the object by value from one application domain to another.

 

For example: serialization is used to save session state in ASP.NET and to copy objects to the Clipboard in Windows Forms. It is also used by remoting to pass objects by value from one application domain to another.

               

Objects Serialization:

 

[Serializable]

public abstract class Animal

{

    public virtual string Name { get; set; }

    public virtual int Arrived { get; set; }

 

    public abstract int SpaceRequired { get; }

}

 

Note: [Serializable] attribute have to use if you want to serialize an object. In the above example we are serializing a entire class called animal.

XML Serialization

                Microsoft introduced xml serialization. XML serialization serializes only the public fields and property values of an object into an XML stream. The central class in XML serialization is the XmlSerializer class, and the most important methods in this class are the Serialize and Deserialize methods. The XmlSerializer creates C# files and compiles them into .dll files to perform this serialization. In .NET Framework 2.0.

 

Items That Can Be Serialized

The following items can be serialized using the XmLSerializer class:

  • Public read/write properties and fields of public classes.
  • Classes that implement ICollection or IEnumerable.

noteNote:

Only collections are serialized, not public properties.

  • XmlElement objects.
  • XmlNode objects.
  • DataSet objects.

Example:

public class OrderForm

{

    public DateTime OrderDate;

}

 

When the above class is serialized then the following code will be generated.

<OrderForm>

    <OrderDate>12/12/01</OrderDate>

</OrderForm>

 

 

 

 

Deserialization:

 

Deserialization is the process of converting a stream into an object. Now we can see object serialization and xml deserialization.

 

protected void DeSerializeMyObject(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>Mobile</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>
</Category>

 

 

In the above code, we are passing one XML string. This will be converted into a form of object. Here XML string is loaded into XmlDocument object and then XmlNodeReader is reading from it. Now XmlSerialize 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.

 

Best Practices

  • Use XML Serialization for better interoperable and flexible but leas on performance
  • Use Binary Serialization if you want to share data which has same model used. Including full type of a type
  • Don't use serialization to transfer large data instead use binary streams
  • Don't use serialization on big object
  • Use custom serialization implementation to select the data as per requirement to serialize instead of including all data. (Use XmlIgnore etc...)
  • Use of XML Serlization for primitive data type models will be faster instead of complex types