//把对象序列化为json对象 public static string GetJson<T>(T obj) { DataContractJsonSerializer json=new DataContractJsonSerializer(typeof(T)); using(MemoryStream ms=new MemoryStream()) { json.WriteObject(ms,obj); string szJson=Encoding.UTF8.GetString(ms.ToArray()); return szJson; } } //把JSON字符串还原为对象 public static T ParseFormJson<T>(string szJson) { T obj=Activator.CreateInstance<T>(); using(MemoryStream ms=new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer dcj=new DataContractJsonSerializer(typeof(T)); return (T)dcj.ReadObject(ms); } }
记住 添加引用 System.ServiceModel.Web 和System.Runtime.Serialization.Json