Tuesday, May 15, 2007

Playing with JSON

I recently had to do some web development work which involved passing an object graph from the ASP.NET server code through to the browser to be consumed by javascript. The last time I had to do something like this was for an intranet application where the browser platform was alwasy going to be IE on Windows. I used XML as the serialization format and consumed it on the browser by instantiating an MSXML DOM. It worked, but it was strictly a Microsoft platform solution and the javascript code was pretty ugly, all that digging around with xpath, urgh! This time the requirement was for an internet application, so I had to choose something that would run on any modern browser. I remembered reading about JSON somewhere as the serialization format of choice for javascript developers, so I decided to give it a whirl. I did a bit of googling and found a couple of .NET JSON libraries, Json.NET by James Newton-King, and Jayrock by Atif Aziz. Atif is also the author of this great introduction to JSON on MSDN, well worth a read. Both of them seemed to fit the bill, but my client was a strictly .NET 1.1 shop, so I had to go with Jayrock since it was the only library with 1.1 support. Jayrock provides quite a comprehensive collection of JSON serialization libraries as well as a JSON RPC IHttpHandler implementation that lets you write JSON 'web serives'. However, all I needed was the serialization function. It worked like a dream for my simple scenario, just one line of code to serialize my object graph to a string:
string jsonText = JsonConvert.ExportToString(myObjectGraph);
Because JSON is effectively native javascript you 'de-serialize' your graph on the client by simply calling 'eval' with your JSON text:
val myObjectGraph = eval(jsonText);
For this simple scenario to work, the objects in your graph have to have a default public constructor and all properties must be settable and gettable, just like when you use the .NET XmlSerializer. But really, so much easier than all that messing around with XML. Of course JSON is extensively used in AJAX applications, even though the 'X' stands for XML :) And there's JSON support built into ASP.NET AJAX (formerly Atlas) in the System.Web.Script.Serialization Namespace, specifically the JavaScriptSerializer class. So if you are doing ASP.NET 2.0 work, you can use that instead of Jayrock. All I need now is an excuse to do some serious Ajax programming.


Anonymous said...

A little dangerous to use eval() take a look a ParseJSON

Mike Hadlow said...

Thanks for the tip. Yes, I seen ParseJSON mentioned elsewhere too.