3

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?

Pharylon
  • 9,796
  • 3
  • 35
  • 59
  • json is json. those are just keys:values as far as it's concerned. what those keys/values represent is up to the code that's producing the data structure which eventually gets encoded into json. json itself couldn't care less if a key is `"id"`, `"$id"`, or `"foobar"`. what you have is perfectly valid json. an array containing two objects, containing further sub-data. – Marc B Oct 23 '15 at 20:27

1 Answers1

4

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:

Community
  • 1
  • 1
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300