Is there a JSON JavaScript library that integrates well with JSON.NET (server side) and supports the "save links" function?

JSON.NET supports circular link serialization, storing all links with the following settings:

JsonSerializerSettings settings = new JsonSerializerSettings(); settings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; settings.PreserveReferencesHandling = PreserveReferencesHandling.All; 

This allows you to run the following code without errors, correctly serialize and deserialize the object with its self-promotion.

 public class SelfReferencingClass { public string Name; public SelfReferencingClass Self; public SelfReferencingClass() {Name="Default"; Self=this;} } SelfReferencingClass s = new SelfReferencingClass(); string jsondata = JsonConvert.SerializeObject( d, settings ); s = JsonConvert.DeserializeObject<SelfReferencingClass>( jsondata, settings ); 

The jsondata line is as follows:

 {"$id":"1","Name":"Default","Self":{"$ref":"1"}} 

The problem is ... how is this JSON.NET feature useful at all without an appropriate client-side JavaScript library that can interpret these links and also supports encoding such links?

Which client library (e.g. JSON.stringify) supports this function / encoding using the "$ id" and "ref ref" fields? If not, is there a way to add support for an existing library?

Adding support would be a fairly simple two-pass process. First, deserialize the entire string, and when creating each object, add it to the dictionary using its value "$ id" as a key. When you come across links (an object consisting only of the "$ ref" property), you can add it to the list of objects + the name of the field that you could return to replace each link found by looking at its key in the final dictionary of created objects.

+7
json serialization circular-reference jsonserializer
source share
1 answer

There are several options:

  • Douglas Crockford's original JSON library has a plugin called cycle.js that resolves round links. Also see this answer, which has an extended version of the method for resolving links: Allow circular links from a JSON object .
  • Cereal , which handles circular links and feature graphs best.
  • CircularJSON , which is very small and does exactly what it says.

Having said that, I will probably reorganize my project to avoid circular references, because JSON is usually the main component, and you probably want to use the main libraries, which are very well tested and supported. One way to avoid circular references is to simply create lightweight pad objects and serialize them instead. Alternatively, you can implement a user interface (if you have access to the class) that overrides serialization behavior. Perhaps you can even automate it using reflection to avoid circular link properties.

+2
source share

All Articles