2

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; }
}
kat1330
  • 5,134
  • 7
  • 38
  • 61
owen
  • 41
  • 1
  • 5
  • 1
    This looks to be a duplicate of [Deserialization of self-referencing properties does not work](http://stackoverflow.com/a/6303647/3744182): *Using references doesn't work with objects that only have constructors with parameters.* You need to make a private parameterless constructor and mark it with `[JsonConstructor]`. – dbc Mar 07 '17 at 02:53
  • 1
    Yes, that post describes the issue that I ran into here, and the solution worked for me. Thanks! – owen Mar 07 '17 at 17:30

0 Answers0