在对象序列化器上设置PreserveReferencesHandling,将会改变所有对象被序列化和反序列化的方式。为了更加细致地控制对象和成员被序列化为一个引用,可以在JsonObjectAttribute, JsonArrayAttribute 和 JsonPropertyAttribute上使用IsReference 属性.
在JsonObjectAttribute, JsonArrayAttribute 上设置IsReference 为true,意味着Json序列化器总是会序列这个类型为一个引用。在JsonPropertyAttribute上设置IsReference为true将只序列化这个属性为一个引用。
[JsonObject(IsReference = true)]
public class EmployeeReference
{
public string Name { get; set; }
public EmployeeReference Manager { get; set; }
}
测试:
List<EmployeeReference> empList = new List<EmployeeReference>();
empList.Add(empRef);
empList.Add(empRef);
string empRefJson = JsonConvert.SerializeObject(empList, Formatting.Indented);
Console.WriteLine(empRefJson);
输出结果:
[
{
"$id": "1",
"Name": "IsReference",
"Manager": null
},
{
"$ref": "1"
}
]
>IReferenceResolver
要想定制引用的生成方式,可以继承自IReferenceResolver接口来使用Json序列化器。