@PatchMapping("/update")
HttpEntity<String> updateOnlyIfFieldIsPresent(@RequestBody Person person) {
if(person.name!=null) //here
}
如何区分未发送的值和空值?如何检测客户端是否发送空字段或跳过字段?
上述解决方案需要对方法签名进行一些更改,以克服请求正文自动转换为 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";
}
}
方法2:-
接收字符串形式的请求正文并检查字符序列(即名称)。
@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";
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)