ILearnable .Net

July 6, 2010

JSON serializing / deserializing, quick and dirty using C# / DataContractSerializer

Filed under: Uncategorized — andreakn @ 06:34

If you need to serialize / deserialize JSON for communicating with javascript for instance you can use the .net DataContractSerializer. The only requirement is that the classes be tagged with [DataContract] and all the members you want to survive the transformation be tagged with [DataMember] (all the built in data types are already [DataContract]s )

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Utilities

 static class JsonUtil
public static string Serialize(object obj)
var jsonSerializer = new DataContractJsonSerializer(obj.GetType());
string returnValue = "";
using (var memoryStream = new MemoryStream())
using (var xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream))
jsonSerializer.WriteObject(xmlWriter, obj);
returnValue = Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
return returnValue;

public static T Deserialize<T>(string json)
T returnValue;
using (var memoryStream = new MemoryStream())
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
var serializer = new DataContractJsonSerializer(typeof (T));
returnValue = (T) serializer.ReadObject(jsonReader);

return returnValue;

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at

%d bloggers like this: