@PatchMapping("/update")
HttpEntity<String> updateOnlyIfFieldIsPresent(@RequestBody Person person) {
if(person.name!=null) //here
}
如何区分未发送的值和空值?如何检测客户端是否发送了空字段或跳过的字段?
最佳答案
上述解决方案需要对方法签名进行一些更改,以克服请求主体自动转换为 POJO(即 Person 对象)的问题。
方法一:-
无需将请求主体转换为 POJO 类(Person),您可以将对象作为 Map 接收并检查键“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";
}
}
方法二:-
以字符串形式接收请求主体并检查字符序列(即名称)。
@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";
}
}
关于java - @RequestBody 如何区分未发送的值和空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40610604/