Serialize and Deserialize JSON

On one of the projects I am working on I needed a way to work get the JSON string generated from some sort of serialization process. If you are working Ajax or MVC controller actions, this work is done for you automatically, but I wanted the string all by itself. After some searching I ran across this article How to: Serialize and Deserialize JSON Data. The article is great, and gave me everything I needed to know, but I thought I would make it a little cleaner and wrap it all up in a class.

Below is the a generic class that will serialize and deserialize JSON:

using System.IO;
using System.Runtime.Serialization.Json;

public class JsonSerializer
{
public JsonSerializer() { }

public string Serialize(T instance)
{
using (MemoryStream stream = new MemoryStream())
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
ser.WriteObject(stream, instance);
stream.Position = 0;

using (StreamReader rdr = new StreamReader(stream))
{
return rdr.ReadToEnd();
}
}
}

public T Deserialize(string json)
{
using (MemoryStream stream = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T result = (T)serializer.ReadObject(stream);
return result;
}
}
}

Update: For a more robust solution, Javier Lozano suggests checking out Json.NET

2 Comments

  • You could port it to extension methods... which makes it a little bit easier to use I guess.

    Cheers,
    Wes

  • Wes:

    You could certainly implement it as an extension method - I'm just not sure which class these methods would be best to extend.

    I chose a class that way the responsibility is centralized. Say you want to convert between XML and Json or something, then you have a place to put it.

    Best,

    Craig

Comments have been disabled for this content.