首页 > 解决方案 > Spring - 忽略请求中的 JSON 属性,但不响应响应

问题描述

这是从GET请求中检索到的有效 Entry 对象http://domain/entry/{id}

{
    "id": 1,
    "description": "ML Books",
    "dueDate": "2017-06-10",
    "paymentDate": "2017-06-10",
    "note": "Distribution de lucros",
    "value": 6500,
    "type": "INCOME",
    "category": {
        "id": 2,
        "name": "Food"
    },
    "person": {
        "id": 3,
        "name": "User",
        "active": true,
        "address": {
            // properties suppressed for better reading
        }
    }
}

在 POST 请求中,我想保存外部对象CategoryPerson只是发送各自的 Id,如下所示:

{
    "description": "NEW ENTRY",
    "dueDate": "2019-06-22",
    "paymentDate": "2019-06-22",
    "note": "Coloured pens",
    "value": 10,
    "type": "INCOME",
    "categoryId": 5,
    "personId": 5
}

为了在没有 Spring 说 person 和 category 对象的情况下保存对象null,我@JsonIgnore在模型中添加了它们,并遵循了这个线程。

它部分工作:

现在,当检索具有相同GET请求的条目时http://domain/entry/{id}

{
    "id": 23,
    "description": "Pens",
    "dueDate": "2019-06-22",
    "paymentDate": "2019-06-22",
    "note": "Coloured pens",
    "value": 10,
    "type": "INCOME",
    "categoryId": null, // It supposed to bring the entire object
    "personId": null // It supposed to bring the entire object
}

PS:categoryId 和 personId 标有@Transient,这就是它为空的原因。

因此,正如标题所述,我只想在 POST 请求(保存它们)中忽略属性 Category 和 Person,而不是在 GET 请求(检索它们)中。

欢迎任何帮助。提前致谢

标签: jsonspringspring-annotations

解决方案


Jackson 为 JsonProperty 添加了READ_ONLYWRITE_ONLY注释参数。因此,您还可以执行以下操作:

@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@Id
@GeneratedValue
private  Long  id;

推荐阅读