Java @RequestBody如何区分未发送值和空值? @PatchMapping(“/update”) HttpEntity UpdateOnlyIffieldPresent(@RequestBody Person){ if(person.name!=null)//此处 }

Java @RequestBody如何区分未发送值和空值? @PatchMapping(“/update”) HttpEntity UpdateOnlyIffieldPresent(@RequestBody Person){ if(person.name!=null)//此处 },java,json,spring,spring-mvc,jackson,Java,Json,Spring,Spring Mvc,Jackson,如何区分未发送的值和空值?如何检测客户端是否发送空字段或跳过字段?上述解决方案需要对方法签名进行一些更改,以克服请求正文自动转换为POJO(即Person对象)的问题 方法1:- 不必将请求主体转换为POJO类(Person),您可以将对象作为映射接收,并检查键“name”是否存在 我想你很难知道,因为到了春天,人们会以同样的方式看待它 @PatchMapping("/update") HttpEntity<String> updateOnlyIfFieldIsPresent(@Re

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

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

方法1:-

不必将请求主体转换为POJO类(Person),您可以将对象作为映射接收,并检查键“name”是否存在


我想你很难知道,因为到了春天,人们会以同样的方式看待它
@PatchMapping("/update")
HttpEntity<String> updateOnlyIfFieldIsPresent(@RequestBody Person person) {
    if(person.name!=null) //here
}
@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"; 
    }

}