Extension Methods for JSON Serialization
January 7th, 2010
Here are some quick extension methods that I created to easily serialize to and from JSON strings.
public static string ToJson(this object obj)
{
var ms = new MemoryStream();
var jsonSerializer = new DataContractJsonSerializer(obj.GetType());
jsonSerializer.WriteObject(ms, obj);
ms.Position = 0;
var sr = new StreamReader(ms);
var json = sr.ReadToEnd();
return json;
}
public static T FromJson<T>(this string jsonString) where T:class
{
var bytes = Encoding.UTF8.GetBytes(jsonString);
var ms = new MemoryStream(bytes);
var jsonSerializer = new DataContractJsonSerializer(typeof(T));
return jsonSerializer.ReadObject(ms) as T;
}