Spring MVC 将请求主体映射到原始类型

标签 spring spring-mvc spring-boot

我想通过 spring mvc 处理简单的 POST 请求。请求正文仅包含一个 int 值。谁能帮我写一下 Action 方法。我的代码如下:

@PostMapping(value = "/update")
@ResponseBody
public ResponseEntity updateLogLevel(@RequestBody int level) {
    try {
        //process request
    } catch (Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
    }
    return ResponseEntity.ok(Constant.STATUS_SUCCESS);
}

但是这段代码抛出异常:
org.springframework.http.converter.HttpMessageNotReadableException",
"message":"JSON parse error: Can not deserialize instance of int out of START_OBJECT token; 
nested exception is 
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int out of START_OBJECT token

我的请求正文:
{
    "level" : 100
}

最佳答案

你在你的有效载荷中发送一个不是整数的对象,只需发送数字

100

关于Spring MVC 将请求主体映射到原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45530748/

相关文章:

java - 跟踪所有实现特定接口(interface)的类?

java - Spring boot中的复合键超过16列

spring - @AuthenticationPrincipal 对象返回 session 值

java - SpringBoot @WebMvcTest 和 @MockBean 没有按预期工作

java - 如何知道哪个插件正在Gradle中添加 “run”任务

spring - 无法在 Grails 3 中动态配置支持 GORM 的数据源

java - 无法构建 Spring Tool Suite 快速入门

java - Spring CustomNumberEditor 解析不是数字的数字

spring-boot - INVALID 不是有效的开始 token

java - 无法执行目标org.springframework.boot :spring-boot-maven-plugin:2. 1.0.RELEASE