Json.Net学习之CustomCreationConverter

前端之家收集整理的这篇文章主要介绍了Json.Net学习之CustomCreationConverter前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

  1. public interface IPerson
  2. {
  3. string FirstName { get; set; }
  4. string LastName { get; set; }
  5. DateTime BirthDate { get; set; }
  6. void Set();
  7. }
  8. public class Employee : IPerson
  9. {
  10. public string FirstName { get; set; }
  11. public string LastName { get; set; }
  12. public DateTime BirthDate { get; set; }
  13. public string Department { get; set; }
  14. public string JobTitle { get; set; }
  15. public void Set()
  16. {
  17. }
  18. }
  19. public class PersonConverter : CustomCreationConverter<IPerson>
  20. {
  21. public override IPerson Create(Type objectType)
  22. {
  23. return new Employee();
  24. }
  25. }


  1. string json = @"[
  2. {
  3. ""FirstName"": ""Maurice"",""LastName"": ""Moss"",""BirthDate"": ""\/Date(252291661000)\/"",""Department"": ""IT"",""JobTitle"": ""Support""
  4. },{
  5. ""FirstName"": ""Jen"",""LastName"": ""Barber"",""BirthDate"": ""\/Date(258771661000)\/"",""JobTitle"": ""Manager""
  6. }
  7. ]";
  8. List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json,new PersonConverter());
  9. IPerson person = people[0];
  10. Console.WriteLine(person.GetType());// CustomCreationConverterTest.Employee
  11. Console.WriteLine(person.FirstName);// Maurice
  12. Employee employee = (Employee)person;
  13. Console.WriteLine(employee.JobTitle);// Support

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

猜你在找的Json相关文章