Newtonsoft.Json JsonHelper
Json.net 简单封装
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 ///12 /// 只序列号需要的字段 13 /// 14 /// 15 /// 16 /// 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 /// 25 /// 转换成json格式 26 /// 27 /// 对象 28 /// 29 public static string GetJson(object obj) 30 { 31 return JsonConvert.SerializeObject(obj); 32 } 33 34 /// 35 /// json格式字符串转化成T类型对象 36 /// 37 /// 类型 38 /// json字符串 39 /// 40 public static T GetModel (string json) 41 { 42 return JsonConvert.DeserializeObject (json); 43 } 44 45 /// 46 /// 反序列化成json属性 47 /// 48 /// json字符串 49 /// 50 public static Newtonsoft.Json.Linq.JProperty DeserialJson(string json) 51 { 52 return JsonConvert.DeserializeObject (json); 53 } 54 55 /// 56 /// 反序列化JSON到给定的匿名对象. 57 /// 58 /// 匿名对象类型 59 /// json字符串 60 /// 匿名对象 61 /// 调用:var objClass = JsonClass.DeserializeAnonymousType(obj.Data.ToString(), nClass[匿名对象]); 62 /// 匿名对象 63 public static T DeserializeAnonymousType (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 /// 76 /// 构造函数 77 /// 78 /// 传入的属性数组 79 /// true:表示props是需要保留的字段 false:表示props是要排除的字段 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 CreateProperties(Type type, 89 90 MemberSerialization memberSerialization) 91 { 92 IList 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 }