【问题标题】:C# Doubly Linked Tree Deserialization Issue [duplicate]C#双向链接树反序列化问题[重复]
【发布时间】:2017-05-17 20:08:28
【问题描述】:

我正在尝试反序列化一棵树,其中每个节点都有其父节点和子节点的引用。序列化树没有问题,但反序列化它不会保留父引用。相反,它变成了一个空值。

我想做什么简化:

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

输出是这样的:

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": []
    }
  ]
}

这是 Json.net 中的错误吗?有没有办法解决这个问题?

【问题讨论】:

  • 我会编写一个递归函数来在反序列化后修复这些引用。

标签: c# json.net deserialization


【解决方案1】:

我不确定 JSON 有什么问题,但是如果您有没有父引用的孩子,那么您可以解决它。

这是 Ed Plunkett 建议的执行:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    相关资源
    最近更新 更多