C # Duplicate linked tree problem

I am trying to deserialize a tree where each node has a reference of both its parent and child. Serializing the tree works without issue, but deserializing it does not preserve the parent reference. Instead, it becomes zero.

What I am trying to simplify:

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));
    }
}

      

Output:

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 a way to fix this?

+3


source to share


1 answer


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

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



public void fixParents(Node parent)
{
    foreach(Node child in parent.Children)
    {
        fixParents(child);
        child.Parent = parent;
    }
}

      

0


source







All Articles