@RequestBody 如何区分未发送的值和空值?

Kam*_*icz 3 java spring json spring-mvc jackson

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

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

not*_*est 5

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

方法一:-

您可以将对象作为 Map 接收并检查键“名称”的存在,而不是将请求正文转换为 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";    
    }


}
Run Code Online (Sandbox Code Playgroud)

方法二:-

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

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

}
Run Code Online (Sandbox Code Playgroud)