1 using System; 2 using System.Linq; 3 using Newtonsoft.Json; 4 using Newtonsoft.Json.Serialization; 5 using System.Collections.Generic; 6 7 namespace TT.Utilities.Json 8 { 9 public static class JsonHelper 10 { 11 /// <summary> 12 /// 只序列号需要的字段 13 /// </summary> 14 /// <param name="obj"></param> 15 /// <param name="arrFiled"></param> 16 /// <returns></returns> 17 public static string GetPartModelJson(object obj, string[] arrFiled) 18 { 19 JsonSerializerSettings jsetting = new JsonSerializerSettings(); 20 jsetting.ContractResolver = new LimitPropsContractResolver(arrFiled); 21 return JsonConvert.SerializeObject(obj, Formatting.Indented, jsetting); 22 } 23 24 /// <summary> 25 /// 转换成json格式 26 /// </summary> 27 /// <param name="obj">对象</param> 28 /// <returns></returns> 29 public static string GetJson(object obj) 30 { 31 return JsonConvert.SerializeObject(obj); 32 } 33 34 /// <summary> 35 /// json格式字符串转化成T类型对象 36 /// </summary> 37 /// <typeparam name="T">类型</typeparam> 38 /// <param name="json">json字符串</param> 39 /// <returns></returns> 40 public static T GetModel<T>(string json) 41 { 42 return JsonConvert.DeserializeObject<T>(json); 43 } 44 45 /// <summary> 46 /// 反序列化成json属性 47 /// </summary> 48 /// <param name="json">json字符串</param> 49 /// <returns></returns> 50 public static Newtonsoft.Json.Linq.JProperty DeserialJson(string json) 51 { 52 return JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JProperty>(json); 53 } 54 55 /// <summary> 56 /// 反序列化JSON到给定的匿名对象. 57 /// </summary> 58 /// <typeparam name="T">匿名对象类型</typeparam> 59 /// <param name="json">json字符串</param> 60 /// <param name="anonymousTypeObject">匿名对象</param> 61 /// 调用:var objClass = JsonClass.DeserializeAnonymousType(obj.Data.ToString(), nClass[匿名对象]); 62 /// <returns>匿名对象</returns> 63 public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject) 64 { 65 T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject); 66 return t; 67 } 68 69 public class LimitPropsContractResolver : DefaultContractResolver 70 { 71 string[] props = null; 72 73 bool retain; 74 75 /// <summary> 76 /// 构造函数 77 /// </summary> 78 /// <param name="props">传入的属性数组</param> 79 /// <param name="retain">true:表示props是需要保留的字段 false:表示props是要排除的字段</param> 80 public LimitPropsContractResolver(string[] props, bool retain = true) 81 { 82 //指定要序列化属性的清单 83 this.props = props; 84 85 this.retain = retain; 86 } 87 88 protected override IList<JsonProperty> CreateProperties(Type type, 89 90 MemberSerialization memberSerialization) 91 { 92 IList<JsonProperty> list = 93 base.CreateProperties(type, memberSerialization); 94 //只保留清单有列出的属性 95 return list.Where(p => 96 { 97 if (retain) 98 { 99 return props.Contains(p.PropertyName); 100 } 101 else 102 { 103 return !props.Contains(p.PropertyName); 104 } 105 }).ToList(); 106 } 107 } 108 } 109 }