@PatchMapping("/update")
HttpEntity<String> updateOnlyIfFieldIsPresent(@RequestBody Person person) {
if(person.name!=null) //here
}
如何区分未发送的值和空值?如何检测客户端是否发送了空或跳过字段?
答案 0 :(得分:2)
上述解决方案需要对方法签名进行一些更改,以克服请求主体自动转换为POJO(即Person对象)。
方法1: -
不是将请求主体转换为POJO类(Person),而是将对象作为Map接收并检查是否存在键&#34; name&#34;。
@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";
}
}