javaspring-bootspring-web

How can I detect if the JSON object within Request body is empty in Spring Boot?


I want to return an error when the body of a REST request is empty (e.g contains only {}) but there is no way to detect if the request body contains an empty JSON or not.

I tried to change @RequestBody(required = true) but it's not working.

@PatchMapping("{id}")
public ResponseEntity<Book> updateAdvisor(@PathVariable("id") Integer id, 
   @Valid @RequestBody  BookDto newBook) {
    Book addedBook = bookService.updateBook(newBook);
    return new ResponseEntity<>(addedBook,HttpStatus.OK);
  }

If the body sent contains an empty JSON I should return an exception. If the body is not empty and at least one element is provided I won't return an error.


Solution

  • Try @RequestBody(required = false)

    This should cause the newBook parameter to be null when there is no request body.

    The above still stands and is the answer to the original question.

    To solve the newly edited question:

    1. Change the @RequestBody BookDto newBook parameter to a String parameter (for example, @RequestBody String newBookJson).
    2. Perform pre-conversion validation (such as, "is the body an empty JSON string value").
    3. If the body contains valid JSON, parse the JSON into to an object (example below).
    @Autowired
    private ObjectMapper objectMapper; // A Jackson ObjectMapper.
    
    @PatchMapping("{id}")
    public ResponseEntity<Book> updateAdvisor(
      @PathVariable("id") Integer id, 
      @Valid @RequestBody String newBookJson)
    {
      if (isGoodStuff(newBookJson)) // You must write this method.
      {
        final BookDto newBook = ObjectMapper.readValue(newBookJson, BookDto.class);
    
        ... do stuff.
      }
      else // newBookJson is not good
      {
        .. do error handling stuff.
      }
    }