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.