Jsonプロローグと反プロローグクラス
2686 ワード
System.runtime.serialization.dll参照を追加します.
public static class JsonSerializer
{
private static ITracing _tracing = TracingManager.GetTracing(typeof(JsonSerializer));
/// <summary>
/// JavaScript (JSON) , JSON 。
/// </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="stream"> </param>
/// <param name="obj"> </param>
public static void Serialize<T>(Stream stream, T obj)
{
JsonSerializeProxy<T>.Default.Serialize(stream, obj);
}
/// <summary>
/// JavaScript (JSON) , 。
/// </summary>
/// <typeparam name="T"> </typeparam>
/// <param name="obj"> </param>
/// <returns>JavaScript (JSON) </returns>
public static string Serialize<T>(T obj)
{
using (MemoryStream ms = new MemoryStream())
{
JsonSerializeProxy<T>.Default.Serialize(ms, obj);
string jsonStr = Encoding.UTF8.GetString(ms.ToArray());
_tracing.InfoFmt("{0} json serialize result: {1}", typeof(T).ToString(), jsonStr);
return jsonStr;
}
}
public static T DeSerialize<T>(string jsonStr)
{
return JsonSerializeProxy<T>.Default.DeSerialize(jsonStr);
}
}
public class JsonSerializeProxy<T>
{
private static readonly JsonSerializeProxy<T> _default = new JsonSerializeProxy<T>();
private DataContractJsonSerializer _serializer;
public static JsonSerializeProxy<T> Default
{
get
{
return _default;
}
}
private JsonSerializeProxy()
{
_serializer = new DataContractJsonSerializer(typeof(T));
}
public void Serialize(Stream stream, T obj)
{
_serializer.WriteObject(stream, obj);
}
/// <summary>
/// JSON
/// </summary>
/// <param name="jsonStr">json </param>
/// <returns></returns>
public T DeSerialize(string jsonStr)
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr));
T obj = (T)_serializer.ReadObject(ms);
return obj;
}
}