.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