Skip to content

Instantly share code, notes, and snippets.

@ridomin
Created August 1, 2016 22:30
Show Gist options
  • Save ridomin/5676402249c5475517ad86d07ef16fc6 to your computer and use it in GitHub Desktop.
Save ridomin/5676402249c5475517ad86d07ef16fc6 to your computer and use it in GitHub Desktop.
DataContractJsonSerializer Sample
public static class Serializer<T>
{
public static T FromJson(string json)
{
var s = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(json)))
{
ms.Position = 0;
return (T)s.ReadObject(ms);
}
}
public static string ToJson(object o)
{
var s = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream())
{
s.WriteObject(ms, o);
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment