zoukankan      html  css  js  c++  java
  • Json.Net学习笔记(十一) CustomCreationConverter

    CustomCreationConverter是一个在序列化过程中提供自定方式去创建一个对象的Json转换器,一旦对象被创建,它将被序列化器填充值。

     public interface IPerson
        {
            string FirstName { get; set; }
            string LastName { get; set; }
            DateTime BirthDate { get; set; }
        }

        public class Employee : IPerson
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public DateTime BirthDate { get; set; }

            public string Department { get; set; }
            public string JobTitle { get; set; }
        }
        public class PersonConverter : CustomCreationConverter<IPerson>
        {
            public override IPerson Create(Type objectType)
            {
                return new Employee();
            }
        }

    这是一个非常简单的例子。更复杂的场景可能包含一个对象工厂或者服务定位器(service locator)用来在运行时解析这个对象。

    测试:   

          string json = @"[
                  {
                    ""FirstName"": ""Maurice"",
                    ""LastName"": ""Moss"",
                    ""BirthDate"": ""\/Date(252291661000)\/"",
                    ""Department"": ""IT"",
                    ""JobTitle"": ""Support""
                  },
                  {
                    ""FirstName"": ""Jen"",
                    ""LastName"": ""Barber"",
                    ""BirthDate"": ""\/Date(258771661000)\/"",
                    ""Department"": ""IT"",
                    ""JobTitle"": ""Manager""
                  }
                ]";

                List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());
                IPerson person = people[0];
                Console.WriteLine(person.GetType());// CustomCreationConverterTest.Employee         
                Console.WriteLine(person.FirstName);// Maurice
                Employee employee = (Employee)person;
                Console.WriteLine(employee.JobTitle);// Support

  • 相关阅读:
    面试题
    iOS 对overflow:scroll使用
    iOS微信页面 长按图片出现【存储图像】和【拷贝】不出现【发送朋友】【保存图片】
    cookie设置和读取以及获取超链接参数
    学习资源链接
    gulp中文乱码问题
    原生ajax基础知识笔记
    Visual Studio Code 插件推荐
    前端开发中一些容易混淆的概念汇总
    jq中的类样式操作与html5中的类样式操作的对比
  • 原文地址:https://www.cnblogs.com/q28633999/p/2078393.html
Copyright © 2011-2022 走看看