Json帮助类以及如何使用
标签:des style class code color width
首先要添加引用System.Runtime.Serialization.
public class JSONHelper
{
public static string Serialize(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize(string json)
{
T obj = Activator.CreateInstance();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}
反序列化:
类名 对象 = (类名)JSONHelper.Deserialize(json字符串);
序列化:
string json字符串 = JSONHelper.Serialize(对象);
Json帮助类以及如何使用,搜素材,soscw.com
Json帮助类以及如何使用
标签:des style class code color width
原文地址:http://www.cnblogs.com/yexiaohui/p/3705543.html
评论