3

I'm trying to deserialize a tree where each node has a reference of both its parent and child. Serializing the tree works without a problem, but deserializing it doesn't preserve the parent reference. Instead it becomes a null.

What what I'm trying to do simplified:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

static class MainClass {
    public static void Main() {
        var node = new Node(null);
        node.AddChild();

        var settings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, Formatting = Formatting.Indented };

        //serializing
        string json1 = JsonConvert.SerializeObject(node, settings);
        Console.WriteLine("Before deserializing:");
        Console.WriteLine(json1);
        Console.WriteLine();

        //deserializing
        node = JsonConvert.DeserializeObject<Node>(json1, settings);

        //serializing again
        string json2 = JsonConvert.SerializeObject(node, settings);
        Console.WriteLine("After deserializing:");
        Console.WriteLine(json2);
        Console.WriteLine();

        Console.ReadLine();
    }
}

[JsonObject(IsReference = true)]
class Node {
    public Node Parent = null;
    public List<Node> Children = new List<Node>();

    public Node(Node parent) {
        this.Parent = parent;
    }

    public void AddChild() {
        this.Children.Add(new Node(parent: this));
    }
}

The output is this:

Before deserializing:
{
  "$id": "1",
  "Parent": null,
  "Children": [
    {
      "$id": "2",
      "Parent": {
        "$ref": "1"
      },
      "Children": []
    }
  ]
}

After deserializing:
{
  "$id": "1",
  "Parent": null,
  "Children": [
    {
      "$id": "2",
      "Parent": null,
      "Children": []
    }
  ]
}

Is this a bug in Json.net? Is there any way to fix this?

Maple
  • 41
  • 3

1 Answers1

0

I'm not sure what the problem is with JSON, but if you have children without parent references, then you can fix it.

Here's an execution of the suggestion by Ed Plunkett:

public void fixParents(Node parent)
{
    foreach(Node child in parent.Children)
    {
        fixParents(child);
        child.Parent = parent;
    }
}
Clay07g
  • 1,105
  • 7
  • 23