Monday, March 16, 2009

Json Extension methods

Extension methods are so cool in your web layer so that you can easily convert your things between Json and your object. All you have to do now is decorate your classes with the DataContract/DataMember attributes. How simple is that?

public static class JsonHelper
{
/// <summary>
///
Converts any object to a JSON string
/// </summary>
/// <param name="value">
The value.</param>
/// <returns></returns>
public static string ToJson(this object value)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(value.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, value);
return Encoding.Default.GetString(ms.ToArray());
}
}

/// <summary>
///
Deserializes the specified json.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">
The value.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
public static T FromJson<T>(this string value)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(value)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}

No comments: