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 $ref
s.
My best guess is that you are after something like this:
Note: If you are de-serializing this class a lot (like de-serializing model from http request in a web application) you'll get better performance creating objects with a pre-compiled factory, rather than with object activator:
Note that it is not possible to get access to a parent, because parent objects are always created after their children. That is you need to read the json that the object consists of to the end to be able fully construct the object and by the time you've read the last bracket of an object, you've already read all its children. When a child parsed there is no parent yet to get the reference of.