Here is the code I have:
@PostMapping @ResponseStatus(HttpStatus.CREATED) public void create(@AuthenticationPrincipal AuthenticatedUser authenticatedUser, @RequestBody Integer restaurantId) { voteService.addVote(authenticatedUser.getUser(), restaurantId); }
Here is the JSON body I pass to this method
{ "restaurantId":1 }
Here is the exception:
"JSON parse error: Cannot deserialize value of type `java.lang.Integer` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.
If I change value to String like this:
@PostMapping @ResponseStatus(HttpStatus.CREATED) public void create(@AuthenticationPrincipal AuthenticatedUser authenticatedUser, @RequestBody String restaurantId) { voteService.addVote(authenticatedUser.getUser(), Integer.parseInt(restaurantId)); }
I have this error:
java.lang.NumberFormatException: For input string: "{ "restaurantId":1 }" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) ~[na:na]
The question is how can I pass a single parameter in JSON body and why do I have these exceptions?
I do appreciate your answers a lot!
Advertisement
Answer
You could use @PathVariable or @RequestParam to accept the restautantid.
@PostMapping(value="/{restaurant_id}") @ResponseStatus(HttpStatus.CREATED) public void create(@AuthenticationPrincipal AuthenticatedUser authenticatedUser, @PathVariable("restaurant_id") Integer restaurantId) { voteService.addVote(authenticatedUser.getUser(), Integer.parseInt(restaurantId)); }
Sample Request
curl -X POST http://localhost/api/restaurants/2