How avoid infinite loop during Json Serialization in Java

旧城冷巷雨未停 提交于 2019-12-20 03:52:48

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/27492342/how-avoid-infinite-loop-during-json-serialization-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!