本文介绍了杰克逊的序列化问题.只有同一实体的第一个对象可以很好地序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个REST投票系统,用户可以在该系统上对餐厅进行投票.我有一个Vote类,其中包含User,Restaurant和Date.

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;

}

我需要找到当天的所有选票.如果一个餐厅有几张票,则只有第一个对象可以很好地序列化.另一个显示餐厅ID而不是餐厅对象,如下所示:

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"
    }
]

因此,肯德基的第一个投票显示完整的餐厅信息,而第二个仅显示ID.汉堡王也一样,接下来的2票.

So first Vote for KFC shows full restaurant info, but second shows only ID. Same for Burger King which is next 2 votes.

可能是个问题吗?

推荐答案

您需要使用com.fasterxml.jackson.annotation.JsonIdentityInfo批注并将其声明为Restaurant类:

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;
    ...
}

另请参阅:

  • Jackson/Hibernate, meta get methods and serialisation
  • Jackson JSON - Using @JsonIdentityReference to always serialise a POJO by id

这篇关于杰克逊的序列化问题.只有同一实体的第一个对象可以很好地序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 18:47