.NET Oject And Json

  在最近的項目開發中,需要將.NET 對象序列化爲Json字符串,傳遞到客戶端瀏覽器,同時,需要將客戶端的Json字符串傳遞到Server,反序列化爲.NET對象,主要有三種方式:

  •   DataContractJsonSerializer

  序列化:

/// <summary>
/// 將.NET對象序列化爲Json
/// </summary>
/// <typeparam name="T">.NET對象類型,此處爲泛型</typeparam>
/// <param name="obj">.NET對象</param>
/// <returns>返回Json字符串</returns>
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string returnString = Encoding.UTF8.GetString(ms.ToArray());
return returnString;
}

  反序列化:

/// <summary>
/// 將Json反序列化爲.NET對象
/// </summary>
/// <typeparam name="T">.NET對象類型</typeparam>
/// <param name="json">序列化字符串</param>
/// <returns>返回.NET對象</returns>
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
  • JavaScriptSerializer

  序列化:

 /// <summary>
/// 將.NET對象序列化爲Json
/// </summary>
/// <typeparam name="T">.NET對象類型,此處爲泛型</typeparam>
/// <param name="obj">.NET對象</param>
/// <returns>返回Json字符串</returns>
public static string Serialize<T>(T obj)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Serialize(obj);
}

  反序列化:

 /// <summary>
/// 將Json反序列化爲.NET對象
/// </summary>
/// <typeparam name="T">.NET對象類型</typeparam>
/// <param name="json">序列化字符串</param>
/// <returns>返回.NET對象</returns>
public static T DeSerialize1<T>(string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}

  我還是比較喜歡使用JavaScriptSerializer

  • Json.NET

  以後使用此庫,再寫如何使用Json.NET如何操作Json



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章