Tuesday, March 25, 2008

.NET 3.5 Features - JSON Serialization

Serialization & Deserialization:
The process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created. Serialization/Deserialization is used to transport or to persist objects.

Types of Serialization :
1. Binary Serialization
2. SOAP Serialization
3. XML Serialization
4. Custom Serialization

.NET 3.5 has new object called DataContractJsonSerliaizer used to JSON serialization for Ajax calls / Javascript calls.

Here i am writing JSONHelper class to Serialize and Deserialize
Add Reference: System.Runtime.Serialization.dll(.NET 3.0), System.ServiceModel.Web.dll(.NET 3.5)

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
public class JSONHelper
{
    public static string Serialize(T obj)
    {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());   
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.Default.GetString(ms.ToArray());
    return retVal;
    }

    public static T Deserialize(string json)
    {

    T obj = Activator.CreateInstance();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();

    return obj;
    }

}

Below class going to use for serialization and Deserialization


[DataContract]
public class Book
{

    private int _id;    private string _name;
    public Book() {}

    public Book(int id, string name)
    {
    _id = id;
    _name = name;
    }

   

    [DataMember]   
    public int Id
    {
    get { return _id; }

    set { _id = value; }
    }

    [DataMember]

    public string Name
    {
    get { return _name; }

    set { _name = value; }
    }
}

How to Use JSONHelper class to Serialize

Book b1 = new Book(1, “ASP.NET 3.5″);
string jsonOutput = JSONHelper.Serialize<Book>(b1);

Serialization output:
{”Id”:1,”Name”:”ASP.NET 3.5″}

How to Use JSONHelper class to Deserialize
Book b2 = JSONHelper.Deserialize<Book>(jsonOutput);

 

Posted by in 02:46:50 | Permalink | No Comments »