Could not write JSON: Infinite recursion (StackOverflowError)

返回json格式的数据

        

        
在controller返回数据到统一json转换的时候,出现了json infinite recursion stackoverflowerror的错误,即json在将对象转换为json格式的数据的时候,出现了无限递归调用的情况。

        
具体的情况如下:

        
HmAppProductMgEntity类中,有个属性:private List<HmMoneyInRecEntity> hmMoneyInRecEntityList;,

        
HmAppProductMgEntity与HmMoneyInRecEntity的关系为 OneToMany;

        
在HmMoneyInRecEntity类中,有属性private HmAppProductMgEntity hmAppProductEntity

        
引用到HmAppProductMgEntity中的字段id,并作为外键。

        
hibernate查询结果正常,可以看到返回的HmAppProductMgEntity对象中,有HmMoneyInRecEntity参数值,但在json转换的时候就出现了无限递归的情况。个人分析,应该是json在序列化HmAppProductMgEntity中的hmMoneyInRecEntityList属性的时候,找到了HmMoneyInRecEntity类,然后序列化HmMoneyInRecEntity类,而HmMoneyInRecEntity类中有hmAppProductEntity属性,因此,为了序列化hmAppProductEntity属性,json又得去序列化A类,如此递归反复,造成该问题。

        
解决:

        
在HmMoneyInRecEntity类中hmAppProductEntity的getter 方法上加注解@JsonBackReference,这样问题就解决了。

        
@JsonBackReference和@JsonManagedReference:这两个标注通常配对使用,通常用在父子关系中。@JsonBackReference标注的属性在序列化(serialization,即将对象转换为json数据)时,会被忽略(即结果中的json数据不包含该属性的内容)。@JsonManagedReference标注的属性则会被序列化。在序列化时,@JsonBackReference的作用相当于@JsonIgnore,此时可以没有@JsonManagedReference。但在反序列化(deserialization,即json数据转换为对象)时,如果没有@JsonManagedReference,则不会自动注入@JsonBackReference标注的属性(被忽略的父或子);如果有@JsonManagedReference,则会自动注入自动注入@JsonBackReference标注的属性。
@JsonIgnore:直接忽略某个属性,以断开无限递归,序列化或反序列化均忽略。当然如果标注在get、set方法中,则可以分开控制,序列化对应的是get方法,反序列化对应的是set方法。在父子关系中,当反序列化时,@JsonIgnore不会自动注入被忽略的属性值(父或子),这是它跟@JsonBackReference和@JsonManagedReference最大的区别。

        
转自:http://blog.csdn.net/ludengji/article/details/11584281

猜你喜欢

转载自www.cnblogs.com/gaoxiaowei199110/p/12167176.html
今日推荐