【发布时间】:2016-06-06 12:22:26
【问题描述】:
属性的顺序没有定义,所以我希望 JSON 中的属性顺序也没有定义。但是,我发现 Newtonsoft.Json 在有引用时会期望一定的顺序(我使用的是PreserveReferencesHandling = PreserveReferencesHandling.All)。它期望 $id 属性是 JSON 中第一个出现的属性。
我通过以下测试得出了这个结论
string cyclicJson1 = "{\"FirstChild\":{\"OtherChild\":{\"OtherChild\":{\"$ref\":\"1\"},\"Parent\":{\"$ref\":\"0\"},\"$id\":\"2\"},\"Parent\":{\"$ref\":\"0\"},\"$id\":\"1\"},\"SecondChild\":{\"$ref\":\"2\"},\"$id\":\"0\"}\"";
不能被 Newtonsoft.Json 正确反序列化(一些参考是 null 不应该),如下所示:
string cyclicJson2 = "{\"$id\": \"0\",\"FirstChild\": {\"$id\": \"1\",\"OtherChild\": {\"$id\": \"2\",\"OtherChild\": {\"$ref\": \"1\"},\"Parent\": {\"$ref\": \"0\"}},\"Parent\": {\"$ref\": \"0\"},},\"SecondChild\": {\"$ref\": \"2\"}}";
唯一的区别是我手动将$id 属性向前移动,使其成为每个对象的第一个元素。
类定义如下:
class CycleTestParent
{
public CycleTestChild FirstChild { get; set; }
public CycleTestChild SecondChild { get; set; }
public CycleTestParent()
{
FirstChild = new CycleTestChild();
SecondChild = new CycleTestChild();
}
}
private class CycleTestChild
{
public CycleTestParent Parent { get; set; }
public CycleTestChild OtherChild { get; set; }
}
有没有一种方法可以让我使用 Newtonsoft.Json 而不必假设 $id 属性总是首先出现?除了手动使用 JSON 字符串之外,还有其他方法吗?
【问题讨论】:
标签: javascript c# json json.net