JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.76k stars 3.25k forks source link

Feature request: Cyclic references compatible to 'cycle.js' #929

Open sjoerd222888 opened 8 years ago

sjoerd222888 commented 8 years ago

I would like to propose a feature which would allow, maybe with an additional setting, to serialize a cyclic structure such that the format is compatible to the one used by Douglas Crockford's cycle.js. Instead of using $ref and $id the format {"$ref": PATH} where PATH refers to the the referenced object should be used. This implementation as far as I understand seems also compatible to the IETF draft proposal for JSON references (which is an expired draft in the mean-time). Of course the library should also be able to deserialize this format.

As far as I understand there is no possibility yet for me to extend/configure Newtonsoft.Json to support this format yet. Please correct if I am wrong.

Side comment: There already exists a library apparently based on cycle.js that is compatible to the Newtonsoft.json JSON reference format: jsonnetdecycle

rsheptolut commented 7 years ago

Thumbs up for the feature request. JSON originally came from JS, but JS has no out-of-the-box support for circular references. One of the most common approaches of preserving references in javascript is cycle.js. The IETF draft proposal also looks promising and it's in alignment with cycle.js. Seing that Newtonsoft.Json is an industry-standard library for handling JSON, it's a shame that it doesn't support this method of handling references out of the box. Coming from .NET world it's very hard for me to grasp that I need a separate JS library for handling circular objects, it just breaks my heart. But when I realize there's nothing in npm that's compatible with the way Newtonsoft.Json handles references, it just kills me. @JamesNK will you help the poor souls using JS+.NET and support the widely adopted (it seems) way of cycle.js to handle JSON references?

A side comment to the side comment above. JsonNetDecycle works great, but Newtonsoft.Json will not completely understand the stringified output of JsonNetDecycle.decycle() method, unless you specify MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead in your JsonSerializerSettings when deserializing this JSON, because it adds the $id property last for some reason. You also could rewrite JsonNetDecycle.decycle() method to put $ids first, but JSON.stringify() is not guaranteed to stringify your properties in the order you were adding them to an object, so this is not ideal (https://github.com/JamesNK/Newtonsoft.Json/issues/124)