JSON

Json.Net学习笔记(十三) 缩小序列化Json的大小(2)

字号+ 作者:H5之家 来源:H5之家 2017-03-01 16:01 我要评论( )

public class DynamicContractResolver : DefaultContractResolver { private readonly char _startingWithChar; public DynamicContractResolver(char startingWithChar) { _startingWithChar = startingWithChar;

public class DynamicContractResolver : DefaultContractResolver
{
private readonly char _startingWithChar;
public DynamicContractResolver(char startingWithChar)
{
_startingWithChar = startingWithChar;
}

protected override IList<JsonProperty> CreateProperties(JsonObjectContract contract)
{
IList<JsonProperty> properties = base.CreateProperties(contract);

// only serializer properties that start with the specified character
properties =
properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();

return properties;
}
}

public class Book
{
public string BookName { get; set; }
public decimal BookPrice { get; set; }
public string AuthorName { get; set; }
public int AuthorAge { get; set; }
public string AuthorCountry { get; set; }
}

测试:

Book book = new Book
{
BookName = "The Gathering Storm",
BookPrice = 16.19m,
AuthorName = "Brandon Sanderson",
AuthorAge = 34,
AuthorCountry = "United States of America"
};

string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });
Console.WriteLine(startingWithA);
// {
// "AuthorName": "Brandon Sanderson",
// "AuthorAge": 34,
// "AuthorCountry": "United States of America"
// }

string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });
Console.WriteLine(startingWithA);
// {
// "BookName": "The Gathering Storm",
// "BookPrice": 16.19
// }

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • Json.Net学习笔记(四) Json对象的读写

    Json.Net学习笔记(四) Json对象的读写

    2017-02-27 08:02

  • [C++]Json 学习笔记

    [C++]Json 学习笔记

    2017-02-26 18:01

  • Azure机器学习入门(4)模型发布为Web服务

    Azure机器学习入门(4)模型发布为Web服务

    2017-02-24 09:52

  • Node.js学习之模块化机制原理详解

    Node.js学习之模块化机制原理详解

    2017-02-18 16:03

网友点评
>