Monday, 14 March 2011

Serialize and Deserialize using JavaScriptSerializer and JSON

Ever worndered how to serialize your object instance into a JSON string. You can use System.Web.Script.Serialization.JavaScriptSerializer to do this.

public static string SerializeToJSON(T obj)
{
System.Web.Script.Serialization.JavaScriptSerializer scriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

StringBuilder jsonBuilder = new StringBuilder();

scriptSerializer.Serialize(obj, jsonBuilder);

return jsonBuilder.ToString();
}

And it is quite straightforward to deserialise the JSON string into the original object instance

OriginalType obj = (new System.Web.Script.Serialization.JavaScriptSerializer()).Deserialize(JSONString);

No comments:

Post a Comment