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

Spring Boot MVC Post方法传递List<T>请求体格式错误问题

解决Spring Boot MVC接收JSON数组时的400 Bad Request问题

我来帮你搞定这个问题!咱们先从报错信息里抓关键点:

{
"timestamp": 1526647767010,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "Could not read document: Can not instantiate value of type [simple type, class com.careplan.springbootstarter.entity.Customer] from String value ('ZOMRAN KHALED MEDICAL UNIT'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@46f9d4f8; line: 1, column: 21] (through reference chain: java.util.ArrayList[0]->com.careplan.springbootstarter.entity.CarePlanQuotationHistory["customer"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value o"
}

问题根源分析

虽然你的控制器接收的是List<CarePlanHistoryRequest>(其中customer是String类型),但实际处理流程中(大概率是在productService.CarePlanQuotationHistory1方法里,把CarePlanHistoryRequest转换为CarePlanQuotationHistory实体类时),CarePlanQuotationHistory的customer字段是**Customer实体类型**,而不是String。

Jackson在解析JSON时,拿到的是字符串"ZOMRAN KHALED MEDICAL UNIT",但它不知道怎么把这个字符串转换成Customer对象——因为你的Customer类没有提供接受String参数的构造方法,也没有对应的工厂方法。

解决方案

这里给你三种可行的解决思路,根据你的业务场景选择:

1. 给Customer类添加单参String构造方法

如果业务上只需要通过字符串名称来创建Customer实例,直接给Customer类加一个接受String的构造方法,同时保留无参构造(Jackson反序列化可能需要):

public class Customer {
    private String name; // 假设你的Customer类有name字段
    
    // 新增单参构造方法,用于Jackson解析字符串
    public Customer(String name) {
        this.name = name;
    }
    
    // 必须保留无参构造
    public Customer() {}
    
    // getter和setter方法
}

2. 用Jackson的@JsonCreator注解标记工厂方法

如果不想修改构造方法,可以用Jackson提供的@JsonCreator注解,定义一个工厂方法来将字符串转为Customer对象:

import com.fasterxml.jackson.annotation.JsonCreator;

public class Customer {
    private String name;
    
    public Customer() {}
    
    // 标记工厂方法,Jackson会用这个方法把字符串转成Customer实例
    @JsonCreator
    public static Customer fromString(String name) {
        Customer customer = new Customer();
        customer.setName(name);
        return customer;
    }
    
    // getter和setter方法
}

3. 调整实体类字段类型(业务允许的话)

如果你的业务逻辑里,customer其实只是一个名称字符串,不需要单独的Customer实体类,那可以直接把CarePlanQuotationHistory里的customer字段类型改成String,这样Jackson就能直接完成映射,不需要额外处理。

额外注意事项

  • 检查CarePlanHistoryRequest和CarePlanQuotationHistory之间的转换逻辑,确保没有错误地把String类型的customer转成Customer对象;
  • 发送请求时,务必确保请求头的Content-Type设置为application/json,否则Spring无法正确识别并解析JSON请求体。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:33:05