JSON序列化和反序列化

时间:2024-05-12 19:37:26
public class JSONHelper
{
public static string Serialize<T>(T obj)//序列化为JSON
{
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.Default.GetString(ms.ToArray());
return retVal;
} public static T Deserialize<T>(string json)//反序列化为对象
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.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;
}
public static List<T> DeserializeToList<T>(string json)//反序列化成泛型
{ JavaScriptSerializer serializer = new JavaScriptSerializer(); List<T> objs = serializer.Deserialize<List<T>>(json); return objs; }
}
JavaScriptSerializer 需添加system.web.Extensions引用