首页 > 解决方案 > 如何以 JSON 格式发送整数值并在 REST 控制器中接收?

问题描述

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

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

    System.out.println(" Mobile = "+mobile);
}

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

URL : localhost:8080/otp

Body

{
    "mobile":123456
}

但我收到以下异常

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

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

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

    System.out.println(" Mobile = "+mobile);
}

并将输入传递为

{
    "mobile":123456
}

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

 Mobile = {
    "mobile":"123456"
}

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

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

标签: javajsonspringspring-bootspring-restcontroller

解决方案


如果你想像这样发送你的身体:

{
    "mobile":123456
}

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

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

Body:

12345


推荐阅读