Jackson serialization issue. Only first object of the same entity serializes well

喜欢而已 提交于 2021-01-28 15:31:36

问题


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:


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:

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


来源:https://stackoverflow.com/questions/63633994/jackson-serialization-issue-only-first-object-of-the-same-entity-serializes-wel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!