使用前,需引用开源项目类using Newtonsoft.Json
链接:https://pan.baidu.com/s/1QTbTSMNW8jow1YX9WCTblQ
提取码:1jli
1 using System.Collections.Generic; 2 using System.IO; 3 using Newtonsoft.Json; 4 5 namespace Common 6 { 7 /// <summary> 8 /// Json帮助类 9 /// 使用前需引用开源项目类库:Newtonsoft.Json.dll 10 /// </summary> 11 public sealed class JsonHelper 12 { 13 /// <summary> 14 /// 将对象序列化为json格式 15 /// </summary> 16 /// <param name="obj">序列化对象</param> 17 /// <returns>json字符串</returns> 18 public static string SerializeObjct(object obj) 19 { 20 return JsonConvert.SerializeObject(obj); 21 } 22 /// <summary> 23 /// 解析JSON字符串生成对象实体 24 /// </summary> 25 /// <typeparam name="T">对象类型</typeparam> 26 /// <param name="json">json字符串</param> 27 /// <returns></returns> 28 public static T DeserializeJsonToObject<T>(string json) where T:class 29 { 30 JsonSerializer serializer = new JsonSerializer(); 31 StringReader sr = new StringReader(json); 32 object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(T)); 33 T t = obj as T; 34 return t; 35 } 36 /// <summary> 37 /// 解析JSON数组生成对象实体集合 38 /// </summary> 39 /// <typeparam name="T">对象类型</typeparam> 40 /// <param name="json">json数组</param> 41 /// <returns>对象实体集合</returns> 42 public static List<T> DeserializeJsonToList<T>(string json) where T : class 43 { 44 JsonSerializer serializer = new JsonSerializer(); 45 StringReader sr = new StringReader(json); 46 object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>)); 47 List<T> list = obj as List<T>; 48 return list; 49 } 50 } 51 }