c# 使用JSON序列化 DataContractJsonSerializer

c# 能夠使用DataContractJsonSerializer 進行JSON的序例化;json

須要引用命名空間 using System.Runtime.Serialization.Json;c#

當不須要序例化時,只須要在相應的字段上加   [NonSerialized] ui

例如 :string

[NonSerialized]
private double m_UpValue;it

 

下面給出序例化的過程:io

/// <summary>
/// Serialize T to string
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static string Serialize<T>(T item)
{
if (item == null) return string.Empty;coding

var serializer = new DataContractJsonSerializer(item.GetType());命名空間

using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, item);引用

var sb = new StringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));im

return sb.ToString();
}
}

/// <summary>
/// Deserialize string back to T
/// </summary>
/// <param name="jsonString"></param>
/// <returns></returns>
public static T Deserialize<T>(string jsonString)
{
if (string.IsNullOrEmpty(jsonString)) return default(T);

var ser = new DataContractJsonSerializer(typeof(T));

using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { T jsonObject = (T)ser.ReadObject(ms); return jsonObject; } }

相關文章
相關標籤/搜索