5
@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?

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
Kamil Nękanowicz
  • 6,254
  • 7
  • 34
  • 51
  • I think you will hardly know as it will be seen the same way by Spring MVC – DamCx Nov 15 '16 at 13:17
  • Possible duplicate of [How to distinguish between null and not provided values for partial updates in Spring Rest Controller](https://stackoverflow.com/questions/38424383/how-to-distinguish-between-null-and-not-provided-values-for-partial-updates-in-s) – laffuste Jan 25 '18 at 06:21

1 Answers1

6

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

}
notionquest
  • 37,595
  • 6
  • 111
  • 105