Customcreationconverter for JSON. Net Learning

Source: Internet
Author: User

Customcreationconverter is a JSON converter that provides custom methods to create an object during serialization. Once an object is created, it is filled with values by the serializer.

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)\/"",                ""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

This is a very simple example. A more complex scenario may contain an object factory or servicelocator to parse the object at runtime.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.