Json.Net学习之CustomCreationConverter

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

public interface IPerson
    {
        string FirstName { get; set; }
        string LastName { get; set; }
        DateTime BirthDate { get; set; }
         void 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 void Set()
        {
        }
    }
    public class PersonConverter : CustomCreationConverter<IPerson>
    {
        public override IPerson Create(Type objectType)
        {
            return new Employee();
        }
    }


string json = @"[
              {
                ""FirstName"": ""Maurice"",""LastName"": ""Moss"",""BirthDate"": ""\/Date(252291661000)\/"",""Department"": ""IT"",""JobTitle"": ""Support""
              },{
                ""FirstName"": ""Jen"",""LastName"": ""Barber"",""BirthDate"": ""\/Date(258771661000)\/"",""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

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

相关文章

AJAX是一种基于JavaScript和XML的技术,能够使网页实现异步交...
在网页开发中,我们常常需要通过Ajax从后端获取数据并在页面...
在前端开发中,经常需要循环JSON对象数组进行数据操作。使用...
AJAX(Asynchronous JavaScript and XML)是一种用于创建 We...
AJAX技术被广泛应用于现代Web开发,它可以在无需重新加载页面...
Ajax是一种通过JavaScript和HTTP请求交互的技术,可以实现无...