Json.Net学习笔记(十二) 协议解析
IContractResolver接口提供了一种方法去定制序列化器如何去序列化和反序列化.Net对象为Json对象
实现IContractResolver接口,然后为Json序列化器分配一个实例对象,这样你就可以控制对象是否被序列化为Json对象或者Json数组、对象的成员应该被序列化成什么、如何被序列化、及他们被谁调用等。
->DefaultContractResolver
DefaultContractResolver是序列化器默认的解析器,它以虚函数的形式提供了很多扩展功能,可以被覆写(overriden).
->CamelCasePropertyNamesContractResolver
CamelCasePropertyNamesContractResolver继承自DefaultContractResolver,并且简单的覆写了Json属性名为camel命名规则的形式(首字母小写)
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public DateTime ExpiryDate { get; set; }
public string[] Sizes { get; set; }
}
测试:
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json = JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
Console.WriteLine(json);
输出结果:
{
"name": "Widget",
"price": 9.99,
"expiryDate": "\/Date(1292868060000)\/",
"sizes": [
"Small",
"Medium",
"Large"
]