.NET 3.5: JSON Serialization using the DataContractJsonSerializer

27. February 2008

In ASP.NET AJAX Extensions v1.0 for ASP.NET 2.0 there is the JavaScriptSerializer class that provides JSON serialization and deserialization functionality. However, in .NET 3.5 the JavaScriptSerializer has been marked obsolete. The new object to use for JSON serialization in .NET 3.5 is the DataContractJsonSerliaizer object. I'm still new to the DataContractJsonSerializer, but here's a summary of what I've learned so far...

Object to Serialize

Here's a simple Person object with First Name and Last Name properties.

public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now in order to serialize our object to JSON using the DataContractJsonSerializer we must either mark it with the Serializable attribute or the DataContract attribute. If we mark the class with the DataContract attribute, then we must mark each property we want serialized with the DataMember attribute.

/// Marked with the Serializable Attribute
[Serializable]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}

/// Marked with the DataContact Attribute
[DataContract]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}

 

Serialization Code

Jere's the most basic code to serialize our object to JSON:

Person myPerson = new Person("Chris", "Pietschmann");

/// Serialize to JSON
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = Encoding.Default.GetString(ms.ToArray());

Our resulting JSON looks like this:

/// Result of Person class marked as Serializable
{"<FirstName>k__BackingField":"Chris","<LastName>k__BackingField":"Pietschmann"}


/// Result of Person class marked as DataContract with
/// each Property marked as DataMember

{"FirstName":"Chris","LastName":"Pietschmann"}

As you can see the first serialization with the class marked with the Serializable attribute isn't quite what we were expecting, but is still JSON. This serialization actually isn't compatible with the client-side JSON Serializer in ASP.NET AJAX.

As you can see the second serialization with the class marked with the DataContract attribute is exactly what we were expecting, and is the same JSON that the old JavaScriptSerializer object would have generated. This is the method of JSON serialization using the DataContractJsonSerializer that you'll need to do if you are going to pass the resulting JSON down to the client to be consumed with ASP.NET AJAX.

 

Deserialization Code

Here's the most basic code to deserialize our object from JSON:

Person myPerson = new Person();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(myPerson.GetType());
myPerson = serializer.ReadObject(ms) as Person;
ms.Close();

 

Controlling the property names in the resulting JSON

When using the DataContract and DataMember attributes, you can tell the DataMember attribute the specific name you want that property to have within the JSON serialization by setting its "Name" named parameter.

Here's an example that will give the name of "First" to the "FirstName" property within the JSON serialization:

[DataMember(Name = "First")]
public string FirstName { get; set; }

The resulting JSON looks like this:

{"First":"Chris","LastName":"Pietschmann"}

 

Here's the code for some Helper methods using Generics to do all the dirty work for you

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JSONHelper
{
    public static string Serialize<T>(T obj)
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, obj);
        string retVal = Encoding.Default.GetString(ms.ToArray());
        ms.Dispose();
        return retVal;
    }

    public static T Deserialize<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        obj = (T)serializer.ReadObject(ms);
        ms.Close();
        ms.Dispose();
        return obj;
    }
}

/// Our Person object to Serialize/Deserialize to JSON
[DataContract]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}


/// Sample code using the above helper methods
/// to serialize and deserialize the Person object

Person myPerson = new Person("Chris", "Pietschmann");

// Serialize
string json = JSONHelper.Serialize<Person>(myPerson);

// Deserialize
myPerson = JSONHelper.Deserialize<Person>(json);

 

What Assembly References does my application need for this?

From the namespace that contains DataContractJsonSerializer you can probably tell that you need to add a reference to the System.Runtime.Serialization assembly. However, you also need to add a reference to the System.ServiceModel.Web assembly.

 

asp.net , , ,



Comments

venjiang
venjiang
3/21/2008 7:26:43 PM #
good.
3/30/2008 4:55:56 AM #
Pingback from blogs.msdn.com

Team Individualism : .net 3.5 - my recent presentation resources
china
china
4/12/2008 5:07:49 AM #
Thank you.very good.
Reza
Reza
4/17/2008 3:26:59 PM #
I am trying to use the above JSON Serializer/Deserializer with Silverlight...but im running into two problems. First off, in the serializer, the retval is being Encoded to the Default type using Encoding.Defailt....  but in SL, the type has to be explicity stated, so I tried using Encoding.Unicode... ,but when I debug it...it gives me an error 'System.Text.Encoding.GetString(byte[])' is inaccessible due to its protection level. Would this JSONHelper not work with Silverlight? Why am I getting the above error message with regards to the protection level?
Thanks
Reza
Reza
4/20/2008 12:09:31 PM #
Chris,
I got your code above to work just fine in Silverlight for regular usage. However, there seems to be a bug with the JSON Serializer in Silverlight. The above serializer works just fine until it hits a nested list. I posted a bug report on the Silverlight forums here http://silverlight.net/forums/t/14224.aspx
Chris Pietschmann
Chris Pietschmann
4/20/2008 1:34:39 PM #
I haven't tried to use this code with Silverlight, so I'm not sure what would be causing the error.
5/31/2008 4:32:59 AM #
Pingback from danrigsby.com

Dan Rigsby  » JavaScriptSerializer Undeprecated in .NET 3.5 SP1
6/3/2008 1:04:52 AM #
Pingback from linqtolife.wordpress.com

JSON ile SerileÅŸtirme ve Ters SerileÅŸtirme « LINQ to Life
6/17/2008 6:04:54 PM #
Pingback from linqtolife.wordpress.com

JSON ile SerileÅŸtirme ve Ters SerileÅŸtirme « LINQ to Life
2/5/2009 5:31:09 PM #
Pingback from musingsfromacube.wordpress.com

Serializing/Deserialzing DateTime values to JSON with the DataContractJsonSerializer « Musings From A Cube
3/5/2009 3:55:44 AM #
Pingback from blog.adrweb.net

JSON serialization in ASP.NET 3.5 - Zaragon blog
3/18/2009 11:58:45 AM #
Pingback from weblogs.asp.net

Problems with Silverlight DataContractJsonSerializer. - Albert Pascual ASP.NET Blog
3/19/2009 5:55:12 PM #
Pingback from alpascual.com

Problems with Silverlight DataContractJsonSerializer. : Al Pascual
8/16/2009 7:11:53 AM #
Pingback from tylermerrick.com

Best Resources for working with JSON and C#.Net | Tyler Merrick
Comments are closed