0

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

1
  • Jackson will not recurse your Object Graph. By this I mean to say that in my experience with it, Jackson seems to show that it will avoid serializing an object it has already serialized. Otherwise, you would constantly have issues with infinite recursion. The best guidance I can give you is to use the tools Jackson gives to guide it in generating the correct JSON, or look up how to do custom marshalling and do it yourself. Commented Feb 3, 2014 at 21:06

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.