Skip to content

Instantly share code, notes, and snippets.

@Fodsuk
Created July 17, 2012 13:57
Show Gist options
  • Save Fodsuk/3129520 to your computer and use it in GitHub Desktop.
Save Fodsuk/3129520 to your computer and use it in GitHub Desktop.
Json Serialisation
public class JsonSerialiser : ISerialiser
{
public string Serialize<T>(T t)
{
var ser = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
public T Deserialize<T>(string jsonString)
{
var ser = new DataContractJsonSerializer(typeof(T));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
ms.Close();
return obj;
}
public dynamic Deserialize(Type type, string jsonString)
{
var ser = new DataContractJsonSerializer(type);
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
var obj = ser.ReadObject(ms);
ms.Close();
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment