Reputation: 2251
I am using jackson to map my java class to JSON. How can I write/design a complex response that contains recursive attributes? I don't know how deep will be my leaf from the tree. I can have a tree with 1 node and 1 value (easy), and a tree with N nodes.
For example, we can have
{
"glossary_0": {
"glossary_1": {
"glossary_2": {
[...]
"glossary_N" : "value"
}
}
}
}
Thank you for your advice
Upvotes: 0
Views: 492
Reputation: 6234
I had a bit of trouble parsing your question so hopefully I'm answering the right thing.
If you're using Jackson 2.x you can use @JsonIdentityInfo
to allow Jackson to replace repeated/recursive object references with an auto-generated ID (and the reverse). I'd recommend using the UUID generator like so:
@JsonIdentityInfo(generator = ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class MyClass {
private MyClass c1;
private MyClass c2;
//getters and setters here
}
For the above, Jackson might generate JSON that looks like this (these aren't valid UUIDs but you get the idea):
{
@id: 'abcd-1234-efgh-5678', //randomly generated
c1: null,
c2: {
@id: '9876-efgh-4321-abcd' //randomly generated,
c1: 'abcd-1234-efgh-5678', //set to the id of the referenced object to prevent infinite recursion
c2: null
}
}
For the above, you'd have to have code to "rehydrate" the JSON object (replace the ID references with the actual referenced objects), and "dehydrate" the object if you're sending it back to the server for JSON to map it back into a Java object. I suggest using UUIDs for this, because it is practically guaranteed that if you see a property value that has already been encountered as an @id
it is actually a reference to that object (and not just a string value that happens to be the same).
Upvotes: 1