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

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