You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过@RequestBody传递对象列表时出现400 Bad Request错误求助

问题:Spring API接收JSON数组报400 Bad Request错误

开发接收前端JSON课程列表的API时,始终返回400 Bad Request错误,相关信息如下:

错误信息

{
  "status": 400,
  "error": "Bad Request",
  "trace": "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `com.vtxlab.course.entity.Courses` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `com.vtxlab.course.entity.Courses` from Array value (token `JsonToken.START_ARRAY`)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:391)
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:343)
	at org.springframework.web.servlet.mvc.method.annotation."
}

API代码

@PostMapping(value = "/courses")
public List<Courses> saveAll(@RequestBody List<Courses> courses) {
  return courseService.saveAll(courses);
}

测试用JSON

[    
{
    "courseName": "DATAANALYSES",
    "courseFee":   "20000.00",
    "startDate": "2022-12-01"
},
{
    "courseName": "CSS",
    "courseFee":   "30000.00",
    "startDate": "2022-12-01"
}
]

排查与解决

问题根源

错误栈核心提示:Cannot deserialize value of type com.vtxlab.course.entity.Courses from Array value,说明Spring MVC尝试将请求体的JSON数组解析为单个Courses对象,类型不匹配直接触发400错误。

具体解决方向

  1. 明确指定请求媒体类型
    在@PostMapping中强制声明接收JSON格式,避免Spring对请求格式的误判:
    @PostMapping(value = "/courses", consumes = MediaType.APPLICATION_JSON_VALUE)
    public List<Courses> saveAll(@RequestBody List<Courses> courses) {
      return courseService.saveAll(courses);
    }
    
  2. 验证前端请求合法性
    • 确认请求头包含Content-Type: application/json,这是Spring识别JSON请求的必要条件。
    • 确认发送的JSON是纯数组结构,没有被额外包裹成对象(比如误传{"data": [/*课程列表*/]})。
  3. 检查实体类兼容性
    • Courses类必须提供无参构造函数,Jackson依赖此创建实例。
    • 核对字段类型匹配:如果实体类中courseFee是Double/BigDecimal类型,需将JSON中的字符串"20000.00"改为数值20000.00,或添加@JsonDeserialize注解适配字符串转数值。
    • 字段名严格区分大小写,若JSON键名与实体类字段名不一致,需用@JsonProperty("courseName")注解做映射。
  4. 排除配置干扰
    若项目自定义了HttpMessageConverter,需确认未覆盖默认的Jackson JSON转换器,避免数组解析逻辑失效。

内容的提问来源于stack exchange,提问作者Ursula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 00:10:49