如果您使用ShouldSerialize
这种方式,那么您的反向引用将不会是反向引用。Employee.Manager
将指向一个不同 Manager
的,而不是在其Employees
属性中包含员工的那个。
您应该改用JsonSerializerSettings.PreserveReferencesHandling
它,它专门设计用于使交叉链接成为可能并避免对象重复。
class Program
{
private static void Main ()
{
var m = new Manager { Attr = "Attr1" };
var e = new Employee { Attr = "Attr1", Manager = m };
m.Employees = new[] { e };
Console.WriteLine(JsonConvert.SerializeObject(m,
new JsonSerializerSettings {
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Formatting = Formatting.Indented,
}));
Console.ReadKey();
}
}
class Manager
{
public Employee[] Employees;
public string Attr;
}
class Employee
{
public Manager Manager;
public string Attr;
}
此代码将输出以下 JSON:
{
"$id": "1",
"Employees": [
{
"$id": "2",
"Manager": {
"$ref": "1"
},
"Attr": "Attr1"
}
],
"Attr": "Attr1"
}
请注意,所有对象现在都具有$id
属性,并且当对象第二次出现在对象图中时,将插入对它的引用而不是对象:{ "$ref": "1" }
。