jansupol / jsonbapi

0 stars 0 forks source link

Support for cyclic references and object deduplication #72

Open jansupol opened 6 years ago

jansupol commented 6 years ago

This is a feature request to enhance JSON-B for 1.1 by supporting serialising objects with cycles using JSON-Pointers.

If you have a data structure

class Person {
  String name;
  Person marriedTo;
}

And the following 2 Person instances: John, marriedTo Lisa; and Lisa, marriedTo John;

Then serialising any of those via JSON-B will likely end up in a stack overflow.

The same problem appears if you have a data structure without cycles but the same Java instance to appear multiple times. When serialising this via JSON-B then the person 'John' might get converted to JSON multiple times. And when receiving this JSON on the other side we will end up with having 3 different instances of 'John'.

The solution we have in Apache Johnzon is to provide a mode to use JsonPointers to reference any subsequent occurences while serialising.

Person john = new Person("John");
Person lisa = new Person("Lisa");
john.marriedTo = lisa;
lisa.marriedTo = john;

We use a Johnzon specific JsonbConfig johnzon.deduplicateObjects. If you serialise with this config flag enabled then you'll end up with the following JSON:

{
 "name":"John",
 "marriedTo": {
   "name":"Lisa",
   "marriedTo":"/"
 }
}

Note the "marriedTo":"/". This value is actually a JsonPointer to the root object (John). And you can also create many deeper nested structures with it. Of course they are not that human readable friendly. But perfect for serialisation and deserialisation.

This is a feature we already implemented in Apache Johnzon. It works really well. https://issues.apache.org/jira/browse/JOHNZON-135 https://issues.apache.org/jira/browse/JOHNZON-141 https://issues.apache.org/jira/browse/JOHNZON-143

jansupol commented 6 years ago