【发布时间】:2021-02-26 21:57:47
【问题描述】:
我一直在努力解决我的项目中的这个问题:是否可以仅在端点具有特定值时使用注释@JsonIgnore?
例如我想在endpoint.equals("xxxxxxxxx")时使用注解,但在endpoint.equals("yyyyyy").时不使用
具有这些关系注释的类有 3 个:
客户
@OneToMany(mappedBy = "ownerOfTheProduct")
@JsonIgnore
private List<Product> ownProducts = new ArrayList<>();
类别
@JsonIgnore
@OneToMany(mappedBy = "category")
private List<Product> products;
产品
@ManyToOne
@JoinTable(name = "PRODUCT_CATEGORY", joinColumns = @JoinColumn(name = "product_id"), inverseJoinColumns = @JoinColumn(name = "category_id"))
private Category category;
@ManyToOne
@JoinTable(name = "CLIENT_PRODUCT", joinColumns = @JoinColumn(name = "product_id"), inverseJoinColumns = @JoinColumn(name = "client_id"))
private Client ownerOfTheProduct;
重点是:
如果我不输入@JsonIgnore,我会收到 StackOverflow 错误,json 进入循环并且不会停止。
"id": 1,
"name": "Product name",
"price": 20.0,
"category": {
"id": 1,
"name": "Cleaning",
"products": [
{
"id": 1,
"name": "Product name",
"price": 20.0,
"category": {
...
当我以不同的方式映射并将@JsonIgnore 放入两个类:Client 和 Product 时,它起作用了,循环并没有发生更多。但是,当我必须使用其他端点时,products 和 ownerOfTheProduct 字段需要通过 api 显示,它不起作用,因为 @JsonIgnore 已注释。
循环已解决
{
"id": 1,
"name": "Product name",
"price": 20.0,
"category": {
"id": 1,
"name": "Cleaning"
},
"ownOfTheProduct": {
"id": 1,
"name": "Edited",
"cpf": "Edited",
"email": "test",
"password": "test"
}
}
其他端点不工作
{
"id": 1,
"name": "Edited",
"cpf": "Edited",
"email": "test",
"password": "test"
}
我希望我使用
@JsonIgnore(ownProducts) 映射的字段完全以这种方式显示在此请求中:
{
"id": 1,
"name": "Edited",
"cpf": "Edited",
"email": "test",
"password": "test"
"ownProducts" [
{
"id": 1,
"name": "Product name",
"price": 20.0,
"category": {
"id": 1,
"name": "Cleaning"
},
]
}
有没有办法改变这种情况?总而言之,我只想将@JsonIgnore 与特定的特定端点一起使用,而不是我的 API 上的每个端点。
我希望你们得到我的问题,无论如何这里是github上存储库的链接:https://github.com/reness0/spring-restapi-ecommerce
【问题讨论】:
标签: java json jpa spring-data-jpa annotations