Assume those hierachical object structure: Tree
➻Branch
➻Leaf
public class Tree
{
public string Name { get; set; }
public List<Branch> Nodes { get; set; } = new List<Branch>();
}
public class Branch
{
public Branch(Tree parent) { Parent = parent; }
public Tree Parent { get; }
public string Name { get; set; }
public List<Leaf> Nodes { get; set; } = new List<Leaf>();
}
public class Leaf
{
public Leaf(Branch parent) { Parent = parent; }
public Branch Parent { get; }
public string Name { get; set; }
}
A not so simple serialization output would be (using ReferenceLoopHandling.Serialize
AND PreserveReferencesHandling = PreserveReferencesHandling.Objects
):
{
"$id": "1",
"Name": "AnOakTree",
"Nodes": [
{
"$id": "2",
"Parent": {
"$ref": "1"
},
"Name": "TheLowestBranch",
"Nodes": [
{
"$id": "3",
"Parent": {
"$ref": "2"
},
"Name": "OneOfAMillionLeaf"
}
]
}
]
}
Deserialization works perfectly, nothing to complain! But I'd like to omit reference handling at all to reduce JSON footprint and improve readability.
What's the best way to deserialize JSON without reference informations and invoke the constructors with the correct parameter (the instance of the parent node)? So that the back-references will be recreated by code?