简体   繁体   中英

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 (eg 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.

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.
  }
}

Let's suppose you have a Class BookDto :

 public class BookDto {
       private String bookName;
       private String authorName;
  }

We can use @ScriptAssert Annotation on Class BookDto:

@ScriptAssert(lang = "javascript", script = "_this.bookName != null || _this.authorName != null")
public class BookDto {
       private String bookName;
       private String authorName;
  }

then in the resource/controller Class:

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

Now @Valid annotation will validate whatever we have asserted in the @ScriptAssert annotation's script attribute. ie it now checks if the body of a REST request is empty (eg contains only {}).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM