在第一篇文章中使用的json方法,可以按照需要只处理需要的属性,但却要求属性不能是复杂的类型,例如泛型,数组,其他用户自定义的类等,限制太多,于是自己看看能不能改进,想不到Newtonsoft.Json提供有相关的接口,只需要实现就可以了。只需要继承DefaultContractResolver,并改写一个方法就可以了。
核心代码:
/// <summary> /// 对象转为json,所有属性都输出 /// </summary> /// <typeparam name="ObjType"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string ObjToJsonString<ObjType>(ObjType obj) where ObjType : class { string s = JsonConvert.SerializeObject(obj); return s; } /// <summary> /// 对象转为json,只输出部分属性 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="t">对象类型值</param> /// <param name="propertyInfos">需要json处理的属性名称,以逗号分隔</param> /// <returns></returns> public static string ObjToJsonString<T>(T t, string propertyInfos) where T : class { string[] cols = propertyInfos.Split(new char[] { ‘,‘ }, StringSplitOptions.RemoveEmptyEntries); List<string> _propertyNames = new List<string>(); foreach (string col in cols) { if (!_propertyNames.Contains(col)) { _propertyNames.Add(col); } } string s = JsonConvert.SerializeObject(t, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver(_propertyNames) }); return s; } /// <summary> /// json转为对象 /// </summary> /// <typeparam name="ObjType"></typeparam> /// <param name="JsonString"></param> /// <returns></returns> public static ObjType JsonStringToObj<ObjType>(string JsonString) where ObjType : class { ObjType s = JsonConvert.DeserializeObject<ObjType>(JsonString); return s; } class DynamicContractResolver : DefaultContractResolver { private readonly List<string> _propertyNames; public DynamicContractResolver(List<string> propertyNames) { _propertyNames = propertyNames; } /// <summary> /// 如果属性是对象,需要把这个对象的属性也传给propertyNames, /// 否则处理这个对象属性时,就不包含对应的属性值 /// </summary> /// <param name="type"></param> /// <param name="memberSerialization"></param> /// <returns></returns> protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization); IList<JsonProperty> propertiesReturn = new List<JsonProperty>();//需要json处理的属性 foreach (JsonProperty item in properties) { if (_propertyNames.Contains(item.PropertyName)) { propertiesReturn.Add(item); } } return propertiesReturn; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-11 07:04:11