JSON Serialization using the DataContractJsonSerializer and C#

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:


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

Posted on by Joe in ASP.NET, C#, JavaScript

4 Responses to JSON Serialization using the DataContractJsonSerializer and C#

  1. Walt

    Much grass! That’s a great example. Using it for my website.

  2. Vadim

    Thank you so much)

  3. Michael Vasquez

    what if i have a list of items

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List));
    using ( MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    return (List)serializer.ReadObject(stream);

  4. Chas

    Wow! This is such an elegant way of handling JSON serialization and deserialization. Love it.

Add a Comment