JSON Serialization in .NET

Many of you may be familiar with the use of JSON (JavaScript Object Notation). It is a very tight syntax for expressing the state of an object and is very widely used in Web 2.0/AJAX style development in which objects are passed back and forth between the client using the XmlHttpRequest object out of band to eliminate the need to do a full page refresh.

I found a great article by Rick Strahl that outlines the pros/cons of two built-in .NET serializers: JavaScriptSerializer and DataContractJsonSerializer. You can read about them here.

After using both methods in my own application, I found that another con of the JavaScriptSerializer that is a pro for the DataContractJsonSerializer class is that it requires a public default, parameter-less constructor. This means that I cannot serialize objects that I also would like to make read-only, and therefore, requires a constructor with the properties defined up front.

One point I wanted to make in this post was that the extension class that Rick defines in his post for simplifying DataContractJsonSerializer usage does not work properly. In order to correct it, I added the 'this' keyword to the first parameter so that .NET recognized the static methods as extensions to the object type. In addition, I converted the FromJsonString() method to a generic FromJsonString<T>() method to allow the return object to be strongly typed.

Code is listed below, if you are interested.

image