如何以 JSON 格式发送整数值并在 REST Controller 中接收?

Alt*_*ava 4 java spring json spring-boot spring-restcontroller

我有一个 REST 控制器,我在其中编写了此代码

@PostMapping(value = "/otp")
public void otp(@RequestBody Integer mobile) {

    System.out.println(" Mobile = "+mobile);
}
Run Code Online (Sandbox Code Playgroud)

我使用以下输入从 Postman 调用此方法

URL : localhost:8080/otp

Body

{
    "mobile":123456
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下异常

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of java.lang.Integer out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token
Run Code Online (Sandbox Code Playgroud)

如果我将 String 作为这样的参数

@PostMapping(value = "/otp")
public void otp(@RequestBody String mobile) {

    System.out.println(" Mobile = "+mobile);
}
Run Code Online (Sandbox Code Playgroud)

并将输入作为

{
    "mobile":123456
}
Run Code Online (Sandbox Code Playgroud)

现在它在控制台中打印如下

 Mobile = {
    "mobile":"123456"
}
Run Code Online (Sandbox Code Playgroud)

但我只想要这个值123456。如何达到我的要求?

注意:我不想创建任何额外的 POJO 类,甚至我不想使用查询/路径参数发送数据。

Jai*_*o99 6

如果您想发送您的身体,例如:

{
    "mobile":123456
}
Run Code Online (Sandbox Code Playgroud)

您将创建另一个对象来接收该值。

但是如果您只想接受整数值而没有任何其他对象,则不会将 json 对象放入请求正文中,而只会放入整数本身。

Body:

12345