View Code
public static T Json2Obj<T>(string json) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } public static string Obj2Json<T>(T obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); return Encoding.UTF8.GetString(ms.ToArray()); } }
需要引用System.Runtime.Serialization和System.ServiceModel.Web