1

I retrieve a list of Brothers using hibernate

public class Brother {
    public int brotherId;
    public string name;

    public List<Brother> brothers;

    public Brother()
    {
        brothers = new ArrayList<Brother>();
    }

    //Getter Setter
} 

Hibernate is configured using lazy select in brothers list, this in Java side works, But the problem is when I want to serialize a Brother object to JSON.

I've got org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError)

for Example Bryan can have Mark as brother an viceversa...

How I can solve it? is there any way to indicate max number of recursion to jackson libraries?

my code, it is really simple.

Brother brother = this.myservice.getBrother(4);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(brother));
UserMan
  • 471
  • 2
  • 10
  • 20
  • could you add the code how you use Jackson? – ServerSideCat Dec 15 '14 at 20:19
  • 2
    You can use `@JsonIgnore` and for Jackson > 1.6 use : `@JsonManagedReference`, `@JsonBackReference` on attributes to avoid infinite recursion. – sol4me Dec 15 '14 at 20:19
  • I will test. but if I use JsonIgnore the brother list will be ignored, I don't want that. will @JsonBackReference generate something like this? { "brotherId": 4, "name": "bryan", "brothers": [ { "brotherId": 3, "name": "mark", "brothers": null } ] } – UserMan Dec 15 '14 at 20:29
  • Can you post more code , and sample input / output . Also from future please use @sol4me that way I will be notified if you will write something to me. – sol4me Dec 15 '14 at 20:58

1 Answers1

4

Issue is arising because of Circular Reference.

Since Jackson 1.6 you can use two annotations to solve the infinite recursion problem without ignoring the getters/setters during serialization: @JsonManagedReference and @JsonBackReference.

refer here for more

Community
  • 1
  • 1
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116