在最近的项目开发中,需要将.NET 对象序列化为Json字符串,传递到客户端浏览器,同时,需要将客户端的Json字符串传递到Server,反序列化为.NET对象,主要有三种方式:
- DataContractJsonSerializer
序列化:
////// 将.NET对象序列化为Json /// ///.NET对象类型,此处为泛型 /// .NET对象 ///返回Json字符串 public static string Serialize(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; }
反序列化:
////// 将Json反序列化为.NET对象 /// ///.NET对象类型 /// 序列化字符串 ///返回.NET对象 public static T Deserialize(string json) { T obj = Activator.CreateInstance (); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)); DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); obj = (T)serializer.ReadObject(ms); ms.Close(); return obj; }
- JavaScriptSerializer
序列化:
////// 将.NET对象序列化为Json /// ///.NET对象类型,此处为泛型 /// .NET对象 ///返回Json字符串 public static string Serialize(T obj) { System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return serializer.Serialize(obj); }
反序列化:
////// 将Json反序列化为.NET对象 /// ///.NET对象类型 /// 序列化字符串 ///返回.NET对象 public static T DeSerialize1(string json) { System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return serializer.Deserialize (json); }
我还是比较喜欢使用JavaScriptSerializer
- Json.NET
以后使用此库,再写如何使用Json.NET如何操作Json