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