X

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!
Categories: ASP.NET

View Comments (1)

  • 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.

Related Post