ASP.NET: Serializing and deserializing JSON objects

Posted by DigiMortal on ASP.net Weblogs See other posts from ASP.net Weblogs or by DigiMortal
Published on Tue, 28 Dec 2010 02:01:49 GMT Indexed on 2010/12/28 2:54 UTC
Read the original article Hit count: 318

Filed under:
|

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.

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about Web Development