ASP.NET: Serializing and deserializing JSON objects

ASP.NET offers very easy way to serialize objects to JSON format. Also it is easy to deserialize JSON objects using same library. In this posting I will show you how to serialize and deserialize JSON objects in ASP.NET.

All required classes are located in System.Servicemodel.Web assembly. There is namespace called System.Runtime.Serialization.Json for JSON serializer.

To serialize object to stream we can use the following code.

var serializer = new DataContractJsonSerializer(typeof(MyClass));
serializer.WriteObject(myStream, myObject);

To deserialize object from stream we can use the following code. CopyStream() is practically same as my Stream.CopyTo() extension method.

var serializer = new DataContractJsonSerializer(typeof(MyClass));

using (var stream = response.GetResponseStream())
using (var ms = new MemoryStream
())
{
    CopyStream(stream, ms);
    results = serializer.ReadObject(ms)
as MyClass;
}

Why I copied data from response stream to memory stream? Point is simple – serializer uses some stream features that are not supported by response stream. Using memory stream we can deserialize object that came from web.

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    One thought on “ASP.NET: Serializing and deserializing JSON objects

    • December 28, 2010 at 5:41 am
      Permalink

      Sweet. I used to use James Newton-King’s JSON.NET library (which is pretty good), but with this one, it’s one external dependency less. Thanks for heads up.

    Leave a Reply

    Your email address will not be published. Required fields are marked *