• 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"
      ]

  • 相关阅读:
    Ajax实现动态的二级级联菜单
    使用 Struts 2 实现国际化
    使用 Struts2 校验器校验用户注册信息
    Python基础 9.正则
    Python基础 8.迭代器 生成器 包
    Python基础 7.异常
    Python基础 6 .文件操作
    Python基础 5.类
    Python基础 4.函数
    Python基础 3 控制流程
  • 原文地址:https://www.cnblogs.com/q28633999/p/2078395.html
Copyright © 2020-2023  润新知