public class Common { /// <summary> /// 解析json对象为C#对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T JsonToObj<T>(string json) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); T obj; using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { obj = (T)ser.ReadObject(ms); } return obj; } /// <summary> /// 将对象转换为json /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string ObjToJson(object obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); StringBuilder sb = new StringBuilder(); sb.Append(Encoding.UTF8.GetString(ms.ToArray())); return sb.ToString(); } } } public static class JSONExtension { public static string ToJSON(this object obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); return Encoding.Default.GetString(ms.ToArray()); } } public static T ParseJSON<T>(this string str) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } } Common与JSONExtension均可以实现