using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ServiceModel.Web;///记得引用这个命名空间 using System.Runtime.Serialization.Json; using System.IO; using System.Text;
///<summary> /// Json反序列化,用于接收客户端Json后生成对应的对象 ///</summary> ///<typeparam name="T">对象类型</typeparam> ///<param name="jsonString">JSON字符串</param> ///<returns>对象实体</returns> publicstatic T ParseFormJson<T>(string jsonString) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms); } }
///<summary> /// JSON序列化 ///</summary> publicstaticstring JsonSerializer<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; }
///<summary> /// JSON反序列化 ///</summary> publicstatic T JsonDeserialize<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } } }