@RequestBody如何区分未发送的值和空值? [英] @RequestBody how to differentiate an unsent value from a null value?

查看:1529
本文介绍了@RequestBody如何区分未发送的值和空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@PatchMapping("/update")
HttpEntity<String> updateOnlyIfFieldIsPresent(@RequestBody Person person) {
    if(person.name!=null) //here
}

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

how to differentiate an unsent value from a null value? How can I detect if client sent null or skipped field?

推荐答案

上述解决方案需要对方法签名进行一些更改才能克服请求体自动转换为POJO(即Person对象)。

The above solutions would require some change in the method signature to overcome the automatic conversion of request body to POJO (i.e. Person object).

方法1: -

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

Instead of converting the request body to POJO class (Person), you can receive the object as Map and check for the existence of the key "name".

@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";    
    }


}

方法2: -

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

Receive the request body as String and check for the character sequence (i.e. name).

@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"; 
    }

}

这篇关于@RequestBody如何区分未发送的值和空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆