【问题标题】:Json.Net issue with order of reference properties in JSONJson.Net JSON 中引用属性的顺序问题
【发布时间】: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


    【解决方案1】:

    您需要在这里将MetadataPropertyHandling 设置为MetadataPropertyHandling.ReadAhead

    JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
    {                    
        MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
    };
    

    默认情况下,出于性能原因,元数据属性应位于对象 JSON 的开头。使用此属性,您可以更改解析器行为以在对象 JSON 内的任何位置查看它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多