【问题标题】:@RequestBody how to differentiate an unsent value from a null value?@RequestBody 如何区分未发送的值和空值?
【发布时间】:2017-03-29 09:08:08
【问题描述】:
@PatchMapping("/update")
HttpEntity<String> updateOnlyIfFieldIsPresent(@RequestBody Person person) {
    if(person.name!=null) //here
}

如何区分未发送的值和空值?如何检测客户端是否发送了空字段或跳过的字段?

【问题讨论】:

标签: java json spring spring-mvc jackson


【解决方案1】:

上述解决方案需要对方法签名进行一些更改,以克服请求正文到 POJO(即 Person 对象)的自动转换。

方法一:-

您可以将对象作为 Map 接收并检查键“name”是否存在,而不是将请求正文转换为 POJO 类(Person)。

@PatchMapping("/update")
public String updateOnlyIfFieldIsPresent1(@RequestBody Map<String, Object> requestBody) {

    if (requestBody.get("name") != null) {
        return "Success" + requestBody.get("name"); 
    } else {
        return "Success" + "name attribute not present in request body";    
    }


}

方法二:-

以字符串形式接收请求正文并检查字符序列(即名称)。

@PatchMapping("/update")
public String updateOnlyIfFieldIsPresent(@RequestBody String requestString) throws JsonParseException, JsonMappingException, IOException {

    if (requestString.contains("\"name\"")) {
        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(requestString, Person.class);
        return "Success -" + person.getName();
    } else {
        return "Success - " + "name attribute not present in request body"; 
    }

}

【讨论】:

    猜你喜欢
    • 2014-04-05
    • 2023-03-30
    • 2018-10-07
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    相关资源
    最近更新 更多