gpt4 book ai didi

C# 双链树反序列化问题

转载 作者:行者123 更新时间:2023-11-30 18:17:22 24 4
gpt4 key购买 nike

<分区>

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

我想做的简化:

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 中的错误吗?有什么办法可以解决这个问题吗?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com