Last active
August 28, 2016 23:33
-
-
Save trcio/10076559 to your computer and use it in GitHub Desktop.
An easy to use JSON serializer/deserializer. Requires the assembly reference of 'System.Runtime.Serialization'.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.Serialization.Json; | |
using System.IO; | |
using System.Text; | |
public static class JsonUtil | |
{ | |
/// <summary> | |
/// Serializes an object to the respectable JSON string. | |
/// </summary> | |
public static string Serialize<T>(T o) | |
{ | |
var s = new DataContractJsonSerializer(typeof(T)); | |
using (var ms = new MemoryStream()) | |
{ | |
s.WriteObject(ms, o); | |
return Encoding.UTF8.GetString(ms.ToArray()); | |
} | |
} | |
/// <summary> | |
/// Deserializes a JSON string to the specified object. | |
/// </summary> | |
public static T Deserialize<T>(string json) | |
{ | |
var s = new DataContractJsonSerializer(typeof(T)); | |
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) | |
{ | |
return (T)s.ReadObject(ms); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment