Json.NET - Quick Starts & API Documentation
CustomCreationConverter
The CustomCreationConverter 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.
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();
}
}
This is an extremely simple example. A more complicated scenario could involve an object factory or service locator which resolves the object at runtime.
//[
// {
// "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());
// Newtonsoft.Json.Tests.Employee
Console.WriteLine(person.FirstName);
// Maurice
Employee employee = (Employee)person;
Console.WriteLine(employee.JobTitle);
// Support