JSON Encoding of .NET Objects

For a recent project, it was a user requirement that we be able to save a snapshot of some statistical data on demand. I decided that the best way to do this would be by saving a JSON representation of the data, since I was going to be providing a JavaScript method to render the data, and for comparisons, at a later date. I knew that .NET had a mechanism to convert an object to JSON, because ASP.NET MVC has a JsonResult object that returns data as a JSON string to the client via the browser. However, my Google-Fu failed me, and my searches didn’t return the mechanism to do this.

I’m using .NET 3.5, and I was appalled at the difficulty I was having, especially since ASP.NET AJAX is standard in .NET 3.5. But all I kept finding were items off the list of C# parsers from the json.org. Those libraries and projects are probably fine, but I was trying to avoid adding a new dependency, and again, I knew this had to be possible in core .NET 3.5.

After cracking open the MS-PL source for ASP.NET MVC, I found my answer: The JavaScript Serializer class!

Now, JSON is a data-interchange format that happens to be syntactically compatible for JavaScript, so I think that name sucks, since I’m storing this data as JSON, but fine Microsoft, call it what you will. And using the class is dead simple.

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json_string = serializer.Serialize(_model.getData());
DataObject obj = serializer.Deserialize<DataObject>(json_string);

I’m not completely happy with this API. My first reaction was that I shouldn’t have to instantiate the JavaScriptSerializer class at all. Apparently this requirement is because I can define a custom JavaScriptTypeResolver to aide the serializer in converting my object to a JSON string, but I would still like to see a Singleton implementation of the JavaScript Serializer that allows me to call the Serialize and Deserialize with the default type resolver, but given that this doesn’t appear to be changing for .NET 4.0, I should probably just get over it.