Spring MVC - JSON 无限递归
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9037955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC - JSON infinite recursion
提问by RKodakandla
I have bi-directional relationship like this...
我有这样的双向关系......
Person.java
人.java
public class Person{
@JsonIgnore
@OneToMany(targetEntity=PersonOrganization.class, cascade=CascadeType.ALL,
fetch=FetchType.EAGER, mappedBy="person")
private Set<PeopleOrg> organization;
.....
}
PersonOrganization.java
个人组织.java
public class PersonOrganization{
@JsonIgnore
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="PERSONID", nullable=false)
private Person person;
}
Even with @JsonIgnoreannotation I am getting infinite recursion error when trying to retrieve Person records. I have tried new annotations in 1.6 version. @JsonBackReferenceand @JsonManagedReference. Even then I am getting infinite recursion..
即使有@JsonIgnore注释,我在尝试检索 Person 记录时也会遇到无限递归错误。我在 1.6 版本中尝试了新的注释。@JsonBackReference和@JsonManagedReference。即便如此,我也得到了无限递归..
With @JsonBackReference("person-organization")on Personand @JsonManagedReference("person-organization")on PersonOrganization
随着@JsonBackReference("person-organization")上Person和@JsonManagedReference("person-organization")上PersonOrganization
org.codehaus.Hymanson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.entity.Person["organization"]->org.hibernate.collection.PersistentSet[0]->com.entity.PersonOrganization["person"]->com.entity.Person["organization"]->org.hibernate.collection.PersistentSet[0]...
Even If I interchange the annotations, I am still getting this exception.. Please let me know if there is something wrong with the mappings or the way I am using JSON annotations. Thanks
即使我交换了注释,我仍然会收到此异常。如果映射或我使用 JSON 注释的方式有问题,请告诉我。谢谢
回答by dwi2
I've run into this before. But after moving @JsonIgnore from private field to getter of the field, infinite recursion is gone. So my wild guess is that @JsonIgnore might no work on private field. However, javadoc or tutorial of Hymanson Java JSON-processor do not mention about this, so I cannot be 100% sure. Just for your information.
我以前遇到过这个。但是在将@JsonIgnore 从私有字段移动到该字段的 getter 之后,无限递归消失了。所以我疯狂的猜测是@JsonIgnore 可能在私有领域不起作用。但是,Hymanson Java JSON-processor 的 javadoc 或教程没有提到这一点,所以我不能 100% 确定。仅供参考。
回答by Venky Reddy
The following link says you should annotate the method used by JSON tool to traverse the object graph, to instruct the it to ignore the traversal.
以下链接表示您应该注释 JSON 工具用于遍历对象图的方法,以指示它忽略遍历。
http://Hymanson.codehaus.org/1.0.1/javadoc/org/codehaus/Hymanson/annotate/JsonIgnore.html
http://Hymanson.codehaus.org/1.0.1/javadoc/org/codehaus/Hymanson/annotate/JsonIgnore.html
In my case I have two objects related like this Product <-> ProductImage. So JSON parser went into an infinite loop with out @JsonIgnore annotation on the following to get methods
在我的情况下,我有两个与此 Product <-> ProductImage 相关的对象。所以 JSON 解析器进入了一个无限循环,下面没有@JsonIgnore 注释来获取方法
@JsonIgnore
public Product getImageOfProduct() {
return imageOfProduct;
}
in ProductImage and
在 ProductImage 和
@JsonIgnore
public Set<ProductImage> getProductImages() {
return productImages;
}
in Product.
在产品中。
With the annotation, things are working fine.
有了注释,一切正常。
回答by Venky Reddy
I know this question isn't specifically about Spring Data REST, but I ran into this exception in the context of Spring Data REST, and wanted to share what the problem was. I had a bidirectional relationship involving an entity with no repository. Creating the repository made the loop disappear.
我知道这个问题不是专门关于 Spring Data REST,但我在 Spring Data REST 的上下文中遇到了这个异常,并想分享问题是什么。我有一个涉及没有存储库的实体的双向关系。创建存储库使循环消失。
回答by Farm
Since Hymanson 1.6 you can use two annotations to solve the infinite recursion problem without ignoring the getters/setters during serialization: @JsonManagedReference and @JsonBackReference.
从 Hymanson 1.6 开始,您可以使用两个注释来解决无限递归问题,而不会在序列化过程中忽略 getter/setter:@JsonManagedReference 和 @JsonBackReference。
For more details refer https://stackoverflow.com/a/18288939/286588
有关更多详细信息,请参阅https://stackoverflow.com/a/18288939/286588
回答by Amimo Benja
Apparently since Hymanson 1.6 you can use @JsonManagedReferenceand @JsonBackReferenceto effectively solve the infinite recursion problem.
显然,从 Hymanson 1.6 开始,您可以使用@JsonManagedReference和@JsonBackReference来有效地解决无限递归问题。
I won't go into the details but this changing you classes to the below format should solve the problem.
我不会详细介绍,但是将您的类更改为以下格式应该可以解决问题。
public class Person{
@OneToMany(targetEntity=PersonOrganization.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="person")
@Column(nullable = true)
@JsonManagedReference
private Set<PeopleOrg> organization;
.....
}
public class PersonOrganization{
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="PERSONID")
@JsonBackReference
private Person person;
}
Basically Hymanson converts Set<PeopleOrg> organization, the forward part of the reference a to json-like format using the marshalling process, it then looks for Person person, the back part of the reference and does not serialize it.
基本上,HymansonSet<PeopleOrg> organization使用编组过程将引用 a 的前向部分转换为类似 json 格式的格式,然后查找Person person引用的后部并且不对其进行序列化。
Credits - Kurt Bourbaki& More info - http://keenformatics.blogspot.co.ke/2013/08/how-to-solve-json-infinite-recursion.html
积分 - Kurt Bourbaki和更多信息 - http://keenformatics.blogspot.co.ke/2013/08/how-to-solve-json-infinite-recursion.html
回答by omkar sirra
If A has B & B has A.
如果 A 有 B & B 有 A。
This is one to onerelationship, but forming a circular relation.
这是一对一的关系,但形成了循环关系。
In any of the class, use JustIgnore annotation.
在任何一个类中,使用 JustIgnore 注释。
class A
{
B b;
}
class B
{
@JsonIgnore
A a;
}
This applies for other relationships also like one to many.
这也适用于其他关系,如一对多。
回答by hamza saber
for me, i have tried @JsonIgnore, @JsonManagedReference/@JsonBackReference but nothing worked, till i read this Exception thrown ["hibernateLazyInitializer"] solution 1and this Exception thrown ["hibernateLazyInitializer"] solution 2
对我来说,我已经尝试过@JsonIgnore、@JsonManagedReference/@JsonBackReference 但没有任何效果,直到我读到这个异常抛出 ["hibernateLazyInitializer"] 解决方案 1和这个异常抛出 ["hibernateLazyInitializer"] 解决方案 2
solution 1 is to change from fetch.LAZY to fetch.EAGER, and solution 2 is using @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}), and of course use @JsonIgnore in both solutions
解决方案 1 是从 fetch.LAZY 更改为 fetch.EAGER,解决方案 2 使用@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}),当然在两种解决方案中都使用 @JsonIgnore
回答by Sai Goud
This exception is because, your constructor field are not proper, please check your constructors properties once again in your classes, and check mapping give properly or not,
这个异常是因为,你的构造函数字段不正确,请在你的类中再次检查你的构造函数属性,并检查映射是否正确,
Keep the two Constructors, first is zero construction and second constructor is with fields and both should be contain the super
保留两个构造函数,第一个是零构造,第二个构造函数是带字段的,两者都应该包含超级
回答by Srini
This might be little old but you can add @JsonIgnore at class level with all properties it should ignore. e.g
这可能有点旧,但您可以在类级别添加 @JsonIgnore 以及它应该忽略的所有属性。例如
@JsonIgnore("productImaes","...")
public class Product{ ...
}
回答by Jing Li
Sometimes the member field may have inner reference to the same class typeof itself, which could cause infinite recursionwhen toJson.
有时构件字段可以具有内参照同一类类型的本身,它可能会导致无限递归时toJson。
E.g.: you have a member field Klass a, while the class definition of that Klass is as below.
例如:您有一个成员字段Klass a,而该 Klass 的类定义如下。
class Klass {
Klass mySibling;
public toString() {
return "something" + mySibling.whateverMethod;
}
}
Solution: refactor the member field, eliminate the inner reference.
解决方法:重构成员字段,消除内部引用。

