在Java中的Json序列化期间如何避免无限循环 [英] How avoid infinite loop during Json Serialization in Java
问题描述
使用hibernate检索兄弟列表
public class Brother {
public int brotherId;
公共字符串名称;
公开列表< Brother>兄弟;
$ b $ public Brother()
{
brothers = new ArrayList< Brother>();
}
// Getter Setter
}
Hibernate在兄弟列表中使用lazy select进行配置,这在Java方面是有效的,
但是问题出在我想将Brother对象序列化为JSON时。
我得到了org.codehaus.jackson.map.JsonMappingException:无限递归(StackOverflowError)
例如,布赖恩可以让马克作为兄弟的反证...
我该如何解决它?是否有任何方法可以指示maxson库的递归最大数量?
我的代码很简单。
兄弟= this.myservice.getBrother(4);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(brother));
/ strong>。
$ b
由于
Jackson 1.6
,您可以使用两个注释来解决无限
递归问题,而不会在
序列化过程中忽略getters / setters: @JsonManagedReference 和 @JsonBackReference 。
blockquote>
请参阅此处了解更多
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));
解决方案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
这篇关于在Java中的Json序列化期间如何避免无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!