Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

json.net - Is the $id token a JSON Standard?

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 };

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'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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...