Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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.

Comments

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# December 27, 2010 9:05 PM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# December 27, 2010 9:05 PM

progg.ru said:

Thank you for submitting this cool story - Trackback from progg.ru

# December 27, 2010 9:06 PM

Twitter Trackbacks for PEIP: ASP.NET: Serializing and deserializing JSON objects Full [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 PEIP: ASP.NET: Serializing and deserializing JSON objects  Full         [asp.net]        on Topsy.com

# December 28, 2010 12:28 AM

Alek Davis said:

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.

# December 28, 2010 12:41 AM

Cerebrado said:

This serializer cannot seralize aggregations.

Here you have a solution for that:

softcero.blogspot.com/.../optimizing-net-json-serializing-and-ii.html

Regards

# December 28, 2010 7:48 AM

Anil Kasalanati said:

Introduction:- With the growth of Web2.0 and the need for faster user experience the spotlight has shifted

# December 29, 2010 10:08 AM