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