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

Postman POST请求中Map格式适配Java POJO@RequestBody的方法

正确的JSON格式映射Map<Integer,String>到Java POJO

嘿,我来帮你解决这个问题!你之前写的JSON格式有个小问题——把myMap当成字符串值了,这样Spring的消息转换器没法自动把它解析成Map<Integer,String>类型。

正确的JSON格式应该是这样的:

{
  "myInt": 10,
  "myMap": {
    "1": "A",
    "2": "B"
  }
}

为什么这样写能行?

  • JSON的键只能是字符串,但Spring默认使用的Jackson库会自动把字符串类型的键(比如"1")转换成Integer类型,完美匹配你POJO里的Map<Integer,String>字段。
  • myInt直接用数字值10,而不是字符串"10",这样能直接映射到POJO的Integer类型字段(如果你的myInt是int类型也没问题)。

对应的Java POJO示例:

public class MyRequest {
    private Integer myInt;
    private Map<Integer, String> myMap;

    // 别忘了添加getter和setter,或者用Lombok的@Data注解简化代码
    public Integer getMyInt() {
        return myInt;
    }

    public void setMyInt(Integer myInt) {
        this.myInt = myInt;
    }

    public Map<Integer, String> getMyMap() {
        return myMap;
    }

    public void setMyMap(Map<Integer, String> myMap) {
        this.myMap = myMap;
    }
}

控制器接收请求的示例:

@RestController
@RequestMapping("/demo")
public class DemoController {
    @PostMapping("/submit")
    public String handlePostRequest(@RequestBody MyRequest request) {
        // 直接使用解析后的字段
        String result = String.format("收到myInt: %d,myMap内容: %s", 
                                      request.getMyInt(), request.getMyMap());
        return result;
    }
}

额外注意事项:

  • 确保你的项目中包含Jackson依赖(Spring Boot项目默认已经集成,无需额外添加)。
  • 如果需要自定义类型转换,可以配置ObjectMapper来调整解析规则,但大部分情况下默认配置就足够用了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:18:28