Search code examples
javajsonspringspring-mvcjackson

@RequestBody how to differentiate an unsent value from a null value?


@PatchMapping("/update")
HttpEntity<String> updateOnlyIfFieldIsPresent(@RequestBody Person person) {
    if(person.name!=null) //here
}

how to differentiate an unsent value from a null value? How can I detect if client sent null or skipped field?


Solution

  • The above solutions would require some change in the method signature to overcome the automatic conversion of request body to POJO (i.e. Person object).

    Method 1:-

    Instead of converting the request body to POJO class (Person), you can receive the object as Map and check for the existence of the key "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";    
        }
    
    
    }
    

    Method 2:-

    Receive the request body as String and check for the character sequence (i.e. name).

    @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"; 
        }
    
    }