I am running into an issue when trying to deserialize nested objects that each contain a reference to their parent object.
I am creating a Seed
object that references a Fruit
object which contains the seed
object. The Fruit
object similarly references a containing Tree
.
When I serialise the Tree
containing the Fruit
and Seed
, the retrieved string is:
{
"$id": "1",
"Fruits": {
"$id": "2",
"pear": {
"$id": "3",
"Parent": {
"$ref": "1"
},
"Seeds": {
"$id": "4",
"black seed": {
"$id": "5",
"Parent": {
"$ref": "3"
}
}
}
}
}
}
When I try to deserialize this string back into a Tree
object, the Parent
property of the Seed
object is null.
So, serialization and immediate deserialization of the Tree
object causes a property value in the pre-serialization Tree
object to be null.
The code that reproduces this issues is:
var tree = new Tree();
var fruit = new Fruit(tree);
tree.Fruits.Add("pear", fruit);
var seed = new Seed(fruit);
fruit.Seeds.Add("black seed", seed);
var objString = JsonConvert.SerializeObject(tree, Formatting.None, new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
var deserializedTree = (Tree)JsonConvert.DeserializeObject(objString, typeof(Tree), new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
The classes are:
public class Tree
{
public Tree()
{
Fruits = new Dictionary<string, Fruit>();
}
public IDictionary<string, Fruit> Fruits { get; set; }
}
public class Fruit
{
public Fruit(Tree parent)
{
Parent = parent;
Seeds = new Dictionary<string, Seed>();
}
public Tree Parent { get; set; }
public IDictionary<string, Seed> Seeds { get; set; }
}
public class Seed
{
public Seed(Fruit parent)
{
Parent = parent;
}
public Fruit Parent { get; set; }
}