• 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

  • 相关阅读:
    android开发中调用python代码(带参数)
    安卓开发中实现自动点击功能、获取网络信息’-博客新人初来乍到,欢迎大佬多多指教。
    一文读懂 Spring Boot、微服务架构和大数据治理三者之间的故事
    EditText搜索关键字,返回结果匹配关键字改变颜色
    Android studio无法创建类和接口问题解决办法。提示 Unable to parse template "Class"
    我的主页
    博客园美化-coffee
    apple面容、指纹验证使用
    iOS数据库FMDB操作
    UIBezierPath绘图基础教程
  • 原文地址:https://www.cnblogs.com/aaa6818162/p/2251127.html
Copyright © 2020-2023  润新知