Download source code
Previously I’d done JSON serialization using the JavaScriptSerializer which is part of AJAX Extensions 1.0, but this is now obsolete.
.NET 3.5 introduced the DataContractJsonSerializer class. The class sits in the System.Runtime.Serialization.Json namespace which is curiously hidden away in the System.ServiceModel.Web assembly.
The DataContractJsonSerializer can serialize a class that contains the Serializable attribute or any class defined as a DataContract.
I have created two generic extension methods to serialize/deserialize JSON using the DataContractJsonSerializer.
The serialization method looks like this:
public static string ToJSON<T>(this T obj) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
return Encoding.Default.GetString(stream.ToArray());
}
}
This can be called on any reference type that is marked as serializable to return a JSON string. For example the following code:
Student student = new Student(txtForename.Text, txtSurname.Text, Convert.ToDateTime(txtDOB.Text)); lblResult.Text = student.ToJSON();
Produces this result:
{“DOB”:”\/Date(412779600000+1100)\/”,”Forename”:”Joe”,”Surname”:”Stevens”}
The code to deserialize looks like this:
public static T FromJSON<T>(this T obj, string json) where T : class
{
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return serializer.ReadObject(stream) as T;
}
}
This allows me to do the following:
Student student = new Student().FromJSON(txtJSON.Text);
Wouldn’t it be nice to have static extension methods so I wouldn’t have to use the new keyword?
In the source code I’ve actually added a new contructor to my Student object which does the deserialization:
public Student(string json)
{
Student student = this.FromJSON(json);
_forename = student.Forename;
_surname = student.Surname;
_dob = student.DOB;
}
All nice and easy!
Download source code






Much grass! That’s a great example. Using it for my website.
Thank you so much)