JSON Serialization–Deserialization

JSON is the new “trending” format used to transfer data between server and client. Today I’m going to start a series of post about Windows Azure Mobile Services, but I want to start very easy with something I’ll need for the next parts.

Here is the code of a helper to serialize and deserialize any object. Start with this using:

using System.Runtime.Serialization.Json;

Here is the static class you can use to serialize and deserialize your objects:

public static class JsonHelper
{
  public static string Serialize<T>(this T value)
     where T : class
  {
     var serializer = new DataContractJsonSerializer(typeof(T));

     using (MemoryStream stream = new MemoryStream())
     {
          serializer.WriteObject(stream, value);
          return Encoding.Default.GetString(stream.ToArray());
     }
  }

  public static T Deserialize<T>(this Stream stream)
     where T : class
  {
     var serializer = new DataContractJsonSerializer(typeof(T));
     return (T)serializer.ReadObject(stream);
  }
}

One thought on “JSON Serialization–Deserialization

Comments are closed.