1 public class JsonHelper 2 { 3 4 #region Json序列化与反序列化 5 6 /// <summary> 7 /// 将json转化为对象 8 /// (需要提前构造好结构一致的Model接取数据,且同名字段才可接取数据) 9 /// </summary> 10 /// <typeparam name="T">对象类型</typeparam> 11 /// <param name="json">Json字符串</param> 12 /// <returns></returns> 13 public T ConvertJsonToObject<T>(string json) 14 { 15 try 16 { 17 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); //传入对象类型 18 MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); //把Json传入内存流中保存 19 T obj = (T)serializer.ReadObject(stream); //使用ReadObject方法反序列化成对象 20 return obj; 21 } 22 catch(Exception ex) { throw ex; } 23 24 } 25 26 /// <summary> 27 /// 将对象转化为Json 28 /// </summary> 29 /// <param name="obj"></param> 30 /// <returns></returns> 31 public string ConvertObjectToJson(object obj) 32 { 33 try 34 { 35 string jsonStr = JsonConvert.SerializeObject(obj); //序列化对象 36 return jsonStr; 37 } 38 catch(Exception ex) { throw ex; } 39 } 40 41 #endregion
注:所用的为using Newtonsoft.Json,需要在VS包管理器下载安装