使用.net 3.5的DataContractJsonSerializer進行JSON Serialization
可能你看到這個東東的時候還不理解它是什么,但是如果在.net之前的版本你用過JavaScriptSerializer方法的話,應該就明白了,它在.net 3.5中取代了JavaScriptSerialize進行JSON的serialization和deserialization功能。
注意:需要引入命名空間
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;(這個.NET Framework 3.5需要添加引用:System.Web.Extensions.dll)
備注:關于另一個json操作類JavaScriptSerializer需要引入命名空間
using System.Web.Script.Serialization;(這個需要添加引用:System.Web.Extensions.dll )
// 右鍵添加引用 System.Runtime.Serialization;
//using System.IO;
//using System.Text;
//using System.Runtime.Serialization;
//using System.Runtime.Serialization.Json;
// Serialize
string json = JsonHelper.Serialize<ReturnObject>(returnObject);
// or string json = JsonHelper.Serialize(returnObject);
// Deserialize
obj = JsonHelper.Deserialize<ReturnObject>(json);
/// <summary>
/// 返回對象
/// </summary>
[DataContract]
public class ReturnObject
{
/// <summary>
/// 返回消息
/// </summary>
[DataMember(Name = "message", Order = 1)]
public string Message { get; set; }
/// <summary>
/// 操作狀態
/// </summary>
[DataMember(Name = "status", Order = 0)]
public string Status { get; set; }
}
/// <summary>
/// Json幫助類
/// </summary>
public class JsonHelper
{
/// <summary>
/// 序列化輸出json字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
}
/// <summary>
/// 反序列化成對象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
T obj = Activator.CreateInstance<T>();
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
return obj;
}
}
}