$ id令牌是JSON标准吗? [英] Is the $id token a JSON Standard?

查看:90
本文介绍了$ id令牌是JSON标准吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Microsoft WebApi 2(使用第三方Json.NET库),假设我返回以下people数组:

Using Microsoft WebApi 2 (which uses the third party Json.NET library), let's say I return the following people array:

var p1 = new Person("Alice");
var p2 = new Person("Bob");
p1.Sibling = p2;
p2.Sibling = p1;
var people = new[] { p1, p2 };

为避免循环引用,Json.NET会输出以下JSON:

To avoid circular references, it Json.NET outputs the following JSON:

[  
   {  
      "$id":"1",
      "Name":"Alice",
      "Sibling":{  
         "$id":"2",
         "Name":"Bob",
         "Sibling":{  
            "$ref":"1"
         }
      }
   },
   {  
      "$ref":"2"
   }
]

Javascript的JSON.parse()方法对此语法一无所知.我查阅了JSON规范,发现指针中使用了$ ref关键字,但没有看到使用$ id关键字的情况.关于Json.NET,这有点古怪吗?还是在JSON规范中只是不被广泛支持?

Javascript's JSON.parse() method doesn't know anything about this syntax. I looked up the JSON spec, and I see uses of the $ref keyword in pointers, but I don't see them using the $id keyword. Is this something quirky about Json.NET? Or is it something in the JSON spec that just isn't widely supported?

推荐答案

否,$id$ref不是JSON标准的一部分(您会注意到保留对象引用.

No, $id and $ref is not part of the JSON standard (you'll notice it is not mentioned anywhere on JSON.org); it is a convention used by Json.Net to tag objects and refer to them for purposes of preserving the references on deserialization. Other JSON libraries may or may not follow the same convention. See Preserving Object References in the Json.Net documentation for more information.

注意:有些javascript方法可以处理Json.Net中的$id/$ref表示法.您可能对以下示例感兴趣:

NB: There are javascript methods that can handle resolving the $id/$ref notation from Json.Net. You may be interested in these examples:

  • Resolve circular references from JSON object
  • How to restore circular references (e.g. "$id") from Json.NET-serialized JSON?

这篇关于$ id令牌是JSON标准吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆