I am trying to extend the JSON.net example given here
http://james.newtonking.com/projects/json/help/CustomCreationConverter.html
I have another sub class deriving from base class/Interface
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Employee : Person
{
public string Department { get; set; }
public string JobTitle { get; set; }
}
public class Artist : Person
{
public string Skill { get; set; }
}
List<Person> people = new List<Person>
{
new Employee(),
new Employee(),
new Artist(),
};
How do I deserialize following Json back to List< Person >
[
{
"Department": "Department1",
"JobTitle": "JobTitle1",
"FirstName": "FirstName1",
"LastName": "LastName1"
},
{
"Department": "Department2",
"JobTitle": "JobTitle2",
"FirstName": "FirstName2",
"LastName": "LastName2"
},
{
"Skill": "Painter",
"FirstName": "FirstName3",
"LastName": "LastName3"
}
]
I don’t want to use TypeNameHandling JsonSerializerSettings. I am specifically looking for custom JsonConverter implementation to handle this. The documentation and examples around this are pretty sparse on the net. I can’t seem to get the the overridden ReadJson() method implementation in JsonConverter right.
Using the standard
CustomCreationConverter, I was struggling to work how to generate the correct type (PersonorEmployee), because in order to determine this you need to analyse the JSON and there is no built in way to do this using theCreatemethod.I found a discussion thread pertaining to type conversion and it turned out to provide the answer. Here is a link: Type converting (archived link).
What’s required is to subclass
JsonConverter, overriding theReadJsonmethod and creating a new abstractCreatemethod which accepts aJObject.The overridden
ReadJsonmethod creates aJObjectand invokes theCreatemethod (implemented by our derived converter class), passing in theJObjectinstance.This
JObjectinstance can then be analysed to determine the correct type by checking existence of certain fields.Example