英文:
Jackson serialization issue. Only first object of the same entity serializes well
问题
我开发了一个REST投票系统,用户可以在餐厅上进行投票。我有一个Vote类,其中包含User、Restaurant和Date。
public class Vote extends AbstractBaseEntity {
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
@NotNull
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "restaurant_id")
private Restaurant restaurant;
@Column(name = "date", nullable = false)
@NotNull
private LocalDate date;
}
我需要找到当天的所有投票。如果有多个人对同一家餐厅投票,只有第一个对象序列化正确。其他对象显示餐厅ID,而不是Restaurant对象,如下所示:
[
{
"id": 100019,
"user": null,
"restaurant": {
"id": 100004,
"name": "KFC"
},
"date": "2020-08-28"
},
{
"id": 100020,
"user": null,
"restaurant": 100004,
"date": "2020-08-28"
},
{
"id": 100021,
"user": null,
"restaurant": {
"id": 100005,
"name": "Burger King"
},
"date": "2020-08-28"
},
{
"id": 100022,
"user": null,
"restaurant": 100005,
"date": "2020-08-28"
}
]
那么问题可能是什么呢?
英文:
I develop a REST voting system where users can vote on restaurants. I have a Vote class which contains User, Restaurant and Date.
public class Vote extends AbstractBaseEntity {
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
@NotNull
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "restaurant_id")
private Restaurant restaurant;
@Column(name = "date", nullable = false)
@NotNull
private LocalDate date;
}
I need to find all votes of the day. And if there are several votes for one restaurant, only first object serializes well. The other ones shows restaurant ID instead of Restaurant object as shown below:
[
{
"id": 100019,
"user": null,
"restaurant": {
"id": 100004,
"name": "KFC"
},
"date": "2020-08-28"
},
{
"id": 100020,
"user": null,
"restaurant": 100004,
"date": "2020-08-28"
},
{
"id": 100021,
"user": null,
"restaurant": {
"id": 100005,
"name": "Burger King"
},
"date": "2020-08-28"
},
{
"id": 100022,
"user": null,
"restaurant": 100005,
"date": "2020-08-28"
}
]
So first Vote for KFC shows full restaurant info, but second shows only ID. Same for Burger King which is next 2 votes.
What could be a problem?
答案1
得分: 1
你需要使用com.fasterxml.jackson.annotation.JsonIdentityInfo
注解,并将其声明在Restaurant
类上:
@JsonIdentityInfo(generator = ObjectIdGenerators.None.class)
class Restaurant {
private int id;
...
}
另请参阅:
英文:
You need to use com.fasterxml.jackson.annotation.JsonIdentityInfo
annotation and declare it for Restaurant
class:
@JsonIdentityInfo(generator = ObjectIdGenerators.None.class)
class Restaurant {
private int id;
...
}
See also:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论