我有一个 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")
的各种组合,但似乎没有任何效果能产生所需的行为。
我应该怎样做才能得到想要的结果?
您可以使用
@JsonValue
或 @JsonGetter