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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM