如何在JSON体传递一个参数,为什么我有一个异常这样做?



下面是我的代码:

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@AuthenticationPrincipal AuthenticatedUser authenticatedUser,
@RequestBody Integer restaurantId) {
voteService.addVote(authenticatedUser.getUser(), restaurantId);
}

这是我传递给这个方法的JSON主体

{
"restaurantId":1
}

这里有一个例外:

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

如果我像这样改变value为String:

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@AuthenticationPrincipal AuthenticatedUser authenticatedUser,
@RequestBody String restaurantId) {
voteService.addVote(authenticatedUser.getUser(), Integer.parseInt(restaurantId));
}

我有这个错误:

java.lang.NumberFormatException: For input string: "{
"restaurantId":1
}"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68) ~[na:na]

问题是我如何在JSON体中传递单个参数,为什么我有这些异常?

我非常感谢你的回答!

你的方法是接受一个字符串,但你的JSON是提供一个数字。

尝试在JSON主体中用引号包装您的restaurantId,因为您的方法将其作为字符串接受。或者将你的方法改为接受restaurantId作为整数。

您可以使用@PathVariable或@RequestParam来接受餐厅。

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

示例请求

curl -X POST  http://localhost/api/restaurants/2

相关内容

最新更新