using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace Quasar.Client.Helper
{
///
/// Provides methods to serialize and deserialize JSON.
///
public static class JsonHelper
{
///
/// Serializes an object to the respectable JSON string.
///
public static string Serialize(T o)
{
var s = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream())
{
s.WriteObject(ms, o);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
///
/// Deserializes a JSON string to the specified object.
///
public static T Deserialize(string json)
{
var s = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)s.ReadObject(ms);
}
}
///
/// Deserializes a JSON stream to the specified object.
///
public static T Deserialize(Stream stream)
{
var s = new DataContractJsonSerializer(typeof(T));
return (T)s.ReadObject(stream);
}
}
}