I have a JSON input whose objects are all derived from a base class along the lines of this:
public abstract class Base
{
public Base Parent { get; set; }
}
I'm trying to create a CustomCreationConverter to set the Parent property of each object to the parent node in the JSON input using ReadJson (except for the root node, of course). Is this possible? I'd rather not have to traverse the objects after creation to set the Parent property.
Example Time!
Say I have this input JSON:
{
"Name": "Joe",
"Children": [
{ "Name": "Sam", "FavouriteToy": "Car" },
{ "Name": "Tom", "FavouriteToy": "Gun" },
]
}
I have the following two classes:
public class Person
{
public Person Parent { get; set; }
public string Name { get; set; }
public List<Child> Children { get; set; }
}
public class Child : Person
{
public string FavouriteToy { get; set; }
}
The Name and FavouriteToy properties deserialise fine, but I want to have the Parent property of any Person object set to, as you'd expect, the actual parent object within the JSON input (presumably using a JsonConverter). The best I've been able to implement so far is recursively traversing each object after deserialisation and setting the Parent property that way.
P.S.
I want to point out that I know I'm able to do this with references inside the JSON itself, but I'd rather avoid that.
Not a duplicate :(
That question refers to creating an instance of the correct derived class, the issue I'm having is finding a way to get context during the deserialisation of the objects. I'm trying to use a JsonConverter's ReadJson method to set a property of a deserialised object to refer to another object within the same JSON input, without using $refs.
I create an example:
hope this helps. Support link: Json .net documentation