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.
Best Answer
Using the standard
CustomCreationConverter
, I was struggling to work how to generate the correct type (Person
orEmployee
), because in order to determine this you need to analyse the JSON and there is no built in way to do this using theCreate
method.I found a discussion thread pertaining to type conversion and it turned out to provide the answer. Here is a link: Type converting.
What's required is to subclass
JsonConverter
, overriding theReadJson
method and creating a new abstractCreate
method which accepts aJObject
.The overridden
ReadJson
method creates aJObject
and invokes theCreate
method (implemented by our derived converter class), passing in theJObject
instance.This
JObject
instance can then be analysed to determine the correct type by checking existence of certain fields.Example