您的位置:首页 > Web前端 > JavaScript

JSON继承DefaultContractResolver根据首字母序列化与反序列对象成员

2015-12-11 15:58 537 查看
1.先创建一个DynamicContractResolver对象,继承DefaultContractResolver,然后重写CreateProperties方法.

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: