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.
Triynko
source share