2015-08-02 18:50:38 +00:00
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Runtime.Serialization.Json;
|
2015-05-27 14:27:57 +00:00
|
|
|
|
using System.Text;
|
|
|
|
|
|
2020-05-31 09:53:14 +00:00
|
|
|
|
namespace Quasar.Client.Helper
|
2015-05-27 14:27:57 +00:00
|
|
|
|
{
|
2020-05-31 09:53:14 +00:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// Provides methods to serialize and deserialize JSON.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static class JsonHelper
|
2015-05-27 14:27:57 +00:00
|
|
|
|
{
|
|
|
|
|
/// <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());
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-05-31 09:53:14 +00:00
|
|
|
|
|
2015-05-27 14:27:57 +00:00
|
|
|
|
/// <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);
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-05-31 09:53:14 +00:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Deserializes a JSON stream to the specified object.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static T Deserialize<T>(Stream stream)
|
|
|
|
|
{
|
|
|
|
|
var s = new DataContractJsonSerializer(typeof(T));
|
|
|
|
|
return (T)s.ReadObject(stream);
|
|
|
|
|
}
|
2015-05-27 14:27:57 +00:00
|
|
|
|
}
|
|
|
|
|
}
|