【发布时间】: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