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

Map<String, Object>参数报400错误:无法将String转为java.util.Map

问题原因与解决方案

问题根源

当使用multipart/form-data格式提交请求时,@ModelAttribute会将每个表单字段的值默认按字符串类型处理。你传入的data值是JSON格式的字符串,但Spring没有内置转换器能直接将该字符串自动反序列化为Map<String, Object>,因此触发了类型转换错误。

解决方案

方案1:添加自定义字符串转Map转换器

创建一个Spring MVC转换器,让框架能自动把JSON字符串转为Map:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.util.Map;

@Component
public class StringToMapConverter implements Converter<String, Map<String, Object>> {

    private final ObjectMapper objectMapper;

    public StringToMapConverter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Map<String, Object> convert(String source) {
        try {
            return objectMapper.readValue(source, new TypeReference<>() {});
        } catch (Exception e) {
            throw new IllegalArgumentException("data参数格式无效,请传入合法JSON字符串", e);
        }
    }
}

添加后Spring会自动识别该转换器,处理data字段的字符串值并转为Map。

方案2:用@RequestPart拆分接收参数

修改控制器方法,单独接收JSON格式的data和其他表单字段:

@PostMapping(value = "/send", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Response> send(
        @RequestPart("data") Map<String, Object> data,
        @RequestPart("file") MultipartFile file,
        @RequestParam("requestId") String requestId,
        @RequestParam("date") String date) {
    RequestModel model = new RequestModel();
    model.setData(data);
    model.setFile(file);
    model.setRequestId(requestId);
    model.setDate(date);
    var response = service.send(model);
    return ResponseEntity.ok(response);
}

Postman中操作:

  • 选择form-data格式
  • data字段的Value类型选raw,格式切换为JSON,输入{ "key": "value" }
  • 其他字段按原有方式填写即可

方案3:拆分Map键值对为独立表单字段

如果Map结构简单,可直接将Map中的每个键拆分为单独的表单字段:

  • 新增Key:data[key],Value:value
  • 若有其他键,按data[键名]的格式添加字段

Spring的@ModelAttribute会自动将这类格式的参数绑定到RequestModel的data Map中,无需额外配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:36:58