1
    class Item
    {
    public string Id;
    public List<Item> Children;
    }

json

    {
        "Id" : "/parent",
        "Children" : [
        {
            "Id" : "/child1"
        }
        ]
    }

I have class for creating nested items. How would I have a child item access the parent's Id field during/after deserialization of the child? Or is there a way to send the parent Id field when the child is to be created?

Example: Parent Id "/parent" Child Id "/child1" I want the child Id "/parent/child1"

For reasons, I cannot use '[OnDeserialized]' after the parent is finished to loop children and change Id. Nor do I have access to change the json files themselves.

John Smith
  • 11
  • 1
  • A JSON object is defined by the [JSON spec](https://www.json.org/json-en.html) to be an *an **unordered** set of name/value pairs* so in general there;s no reason to assume that the `"Id"` property will be encountered before the `"Children"` property. Perhaps for that reason, Json.NET doesn't provide access to the parent while deserializing the child. – dbc May 13 '22 at 23:33
  • There are some workarounds however. See e.g. [Store/retrieve child-parent relationship with JsonConverter](https://stackoverflow.com/q/46774119) or [How can I deserialize instances of a type that has read-only back-references to some container type also being deserialized?](https://stackoverflow.com/q/56316631). Do either of those approaches work for you? – dbc May 13 '22 at 23:33
  • Alternatively you could do everything in an [`[OnDeserialized]`](https://www.newtonsoft.com/json/help/html/SerializationCallbacks.htm) callback. We need to see a [mcve] to get an idea of what might work best. – dbc May 13 '22 at 23:37

0 Answers0