Click or drag to resize
Json.NETCustomCreationConverter
 

The CustomCreationConverterT is a JsonConverter that provides a way to customize how an object is created during JSON deserialization. Once the object has been created it will then have values populated onto it by the serializer.

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

This is an extremely simple example. A more complicated scenario could involve an object factory or service locator which resolves the object at runtime.

CustomCreationConverter Example
 1//[
 2//  {
 3//    "FirstName": "Maurice",
 4//    "LastName": "Moss",
 5//    "BirthDate": "1981-03-08T00:00Z",
 6//    "Department": "IT",
 7//    "JobTitle": "Support"
 8//  },
 9//  {
10//    "FirstName": "Jen",
11//    "LastName": "Barber",
12//    "BirthDate": "1985-12-10T00:00Z",
13//    "Department": "IT",
14//    "JobTitle": "Manager"
15//  }
16//]
17
18List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());
19
20IPerson person = people[0];
21
22Console.WriteLine(person.GetType());
23// Newtonsoft.Json.Tests.Employee
24
25Console.WriteLine(person.FirstName);
26// Maurice
27
28Employee employee = (Employee)person;
29
30Console.WriteLine(employee.JobTitle);
31// Support
See Also