如何使用 Jackson 处理循环依赖

问题描述 投票:0回答:1

我有一个 Spring Boot 3.3.4 应用程序。

我有一个

User
对象,其中包含
Item
对象列表。
Item
对象引用
User
对象。

public class User {
    UUID id;

    String fullName;

    List<Item> items;
}

public class Item {
    UUID id;

    String name;

    User user;
}

当我列出

Item
对象时,我希望 JSON 看起来像这样:

[
   {
      "id": "faf210d5-1eb8-42a7-b3f3-a9546a1fef4f",
      "name":"book",
      "user": "eb3f856a-7c09-4ba2-875c-59af5d4dabcf"
   }
]

因此,我只想拥有拥有该项目的用户的 ID,而不是整个用户对象。

目前我的 JSON 如下所示:

[
   {
      "id":"faf210d5-1eb8-42a7-b3f3-a9546a1fef4f",
      "name":"book",
      "user":{
         "id":"eb3f856a-7c09-4ba2-875c-59af5d4dabcf",
         "fullName":"John Doe",
         "items":[
            {
               "id":"faf210d5-1eb8-42a7-b3f3-a9546a1fef4f",
               "name":"book"
            }
         ]
      }
   }
]

我尝试了使用

@JsonManagedReference
@JsonBackReference
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
的各种组合,但似乎没有任何效果能产生所需的行为。

我应该怎样做才能得到想要的结果?

spring-boot jackson
1个回答
0
投票

您可以使用

@JsonValue
@JsonGetter

© www.soinside.com 2019 - 2024. All rights reserved.