updateOnlyIfFieldIsPresent(@RequestBo...">

@RequestBody how to distinguish an unsent value from a zero value?

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

How to distinguish an unsent value from a zero value? How can I determine if the client sent a null or missing field?

+2
java json spring jackson spring-mvc
source share
1 answer

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

Method 1: -

Instead of converting the request body to the POJO (Person) class, you can get the object as a map and check for the presence of the name key.

 @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: -

Get the request body as a String and check the sequence of characters (for example, 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"; } } 
+2
source share

All Articles