JSON继承DefaultContractResolver根据首字母序列化与反序列对象成员
2015-12-11 15:58
537 查看
1.先创建一个DynamicContractResolver对象,继承DefaultContractResolver,然后重写CreateProperties方法.
2.创建一个Address对象,添加成员变量.
3.序列化与指定首字母相匹配的成员变量
4.运行的结果
JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751
using System; using System.Collections.Generic; using System.Linq; using System.Text; using GongHuiNewtonsoft.Json.Serialization; namespace JSONDemo { public class DynamicContractResolver : DefaultContractResolver { private readonly char _firstChar; public DynamicContractResolver(char firstChar) { this._firstChar = firstChar; } protected override IList<JsonProperty> CreateProperties(Type type, GongHuiNewtonsoft.Json.MemberSerialization memberSerialization) { IList<JsonProperty> propertyList = base.CreateProperties(type, memberSerialization); //仅序列化首字母相匹配的成员 propertyList = propertyList.Where(p => p.PropertyName.StartsWith(_firstChar.ToString())).ToList(); return propertyList; } } }
2.创建一个Address对象,添加成员变量.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace JSONDemo { public class Address { public string Province { get; set; } public string City { get; set; } public string County { get; set; } public string DetailAddress { get{ return County + " " + City + " " + Province; } } } }
3.序列化与指定首字母相匹配的成员变量
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using GongHuiNewtonsoft.Json; using GongHuiNewtonsoft.Json.Serialization; using GongHuiNewtonsoft.Json.Converters; namespace JSONDemo { class Program { static void Main(string[] args) { Address address = new Address { Province = "GuangDong", City = "GuangZhou", County = "PanYu" }; Console.WriteLine("--------------仅序列化首字母是C的成员变量----------"); string firstCharC = JsonConvert.SerializeObject(address, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('C') }); Console.WriteLine(firstCharC); Console.WriteLine("--------------仅序列化首字母是D的成员变量----------"); string firstCharD = JsonConvert.SerializeObject(address, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('D') }); Console.WriteLine(firstCharD); } } }
4.运行的结果
JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751
相关文章推荐
- 将一个map 集合装换成json 字符串,返还给前台
- javascript 调用pdf插件实现自主打印
- js 几种弹窗
- 单选按钮 默认选中
- 简单描述XML和JSON
- Jsp入门实战上
- JSON继承JsonConverter序列化与反序列化重写类属性
- ECSHOP 首页主广告管理 Flash替换成其他js效果的修改
- Ajax跨域、Json跨域、Socket跨域和Canvas跨域等同源策略限制的解决方法
- 将json转换成bean
- JS 打字机效果
- 10009---JavaScript--字符串
- JavaScript 对象属性作实参以及实参对象的callee属性
- Volley Gson Json
- volley JSON请求数据
- jsp低级错误,记下来专贴
- 有关js原型的系列方法
- js控制文字闪烁的代码
- [Servlet&JSP] 初识ServletConfig
- javascript.void(0)依旧会跳转页面问题