1. 程式人生 > >解決Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain

解決Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain

Hibernate 的實體持久化類之的關聯關係當遇到Json序列化/反序列化時導致無限遞迴問題

解決辦法:使用@JsonIdentityInfo註解

從一個英文教程網站上看到的解決辦法翻譯如下

@JsonIdentityInfo用於表示在序列化/反序列化值時使用物件標識 - 例如,處理無限遞迴型別的問題。

在以下示例中 - 我們有一個與UserWithIdentity實體具有雙向關係的ItemWithIdentity實體:

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class,
  property = "id")
public class ItemWithIdentity {
    public int id;
    public String itemName;
    public UserWithIdentity owner;
}

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class,
  property = "id")
public class UserWithIdentity {
    public int id;
    public String name;
    public List<ItemWithIdentity> userItems;
}

現在,我們寫個測試看看如何處理無限遞迴問題:

@Test
public void whenSerializingUsingJsonIdentityInfo_thenCorrect()
  throws JsonProcessingException {
    UserWithIdentity user = new UserWithIdentity(1, "John");
    ItemWithIdentity item = new ItemWithIdentity(2, "book", user);
    user.addItem(item);
 
    String result = new ObjectMapper().writeValueAsString(item);
 
    assertThat(result, containsString("book"));
    assertThat(result, containsString("John"));
    assertThat(result, containsString("userItems"));
}

結果:

{
    "id": 2,
    "itemName": "book",
    "owner": {
        "id": 1,
        "name": "John",
        "userItems": [
            2
        ]
    }
}