Which JSON Serializer to use?


This is an easy one, but just want to make a note for easy reference. JSON is more ubiquitous than ever these days in ASP.Net web development. From AJAX enables web sites to MVC AJAX, JSON is “the” data-interchange format we want to use.

There are 2 possible class libraries that you can use in ASP.net to serialize objects to JSON and back. If you are using WCF and your custom objects are marked as [Data Contratcs], then DataContractJsonSerializer (System.Runtime.Serialization.Json) is the class you want to use. But if you are using an object that you cannot mark as a DataContract (may be part of a third-party component), then you want to use JavaScriptSerializer (System.Web.Script.Serialization).

Here is some code snippets that shows both approaches:

/* Using JavaScriptSerializer */
//Serialize		
String s;
JavaScriptSerializer ser = new JavaScriptSerializer();
ser.MaxJsonLength = Int32.MaxValue;
s = ser.Serialize(obj);

//De-Serialize
JavaScriptSerializer ser = new JavaScriptSerializer();
ser.MaxJsonLength = Int32.MaxValue;
obj = ser.Deserialize(json);
return (obj);



/* Using DataContractJsonSerializer */

//Serialize
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());

//De-Serialize
T obj = Activator.CreateInstance();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
obj = (T)ser.ReadObject(ms);
ms.Close();

Happy programming!

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