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

Java使用Jackson序列化Map类型字段时外层键丢失如何修复

问题原因

这是Jackson使用中非常常见的序列化问题,大量开发者都踩过同类坑。
你遇到的Map字段消失、内部键值直接平铺到外层JSON的现象,根本原因是test_map_key字段对应的getter方法上标记了@JsonAnyGetter注解。
Jackson对@JsonAnyGetter的默认处理逻辑是:将被标注的Map类型字段的所有键值对,直接展开合并到当前对象的外层JSON属性中,不会为该Map字段本身生成独立的嵌套节点,和你现在得到的异常输出完全匹配。

修复方法

按实际场景选择对应处理即可:

  • 无动态属性平铺需求:直接删除test_map_key字段对应getter上的@JsonAnyGetter注解,重新执行序列化即可得到预期的嵌套结构。
  • 需要保留动态属性平铺能力:将test_map_key这个固定嵌套字段,和标注@JsonAnyGetter的动态属性Map拆分为两个独立字段,不要混用。
  • 特殊场景排查:如果删除注解后问题仍然存在,检查是否为该字段配置了自定义JsonSerializer,且序列化逻辑中手动将Map内容写入了外层JSON节点;如果项目使用Lombok,检查类上是否有自动生成@JsonAnyGetter方法的注解配置。
参考实现

符合预期输出的实体类定义:

public class TestEntity {
    private String name;
    // 注意:该字段及对应getter不要加@JsonAnyGetter注解
    private Map<String, List<String>> test_map_key;

    // 标准getter/setter
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<String, List<String>> getTest_map_key() {
        return test_map_key;
    }

    public void setTest_map_key(Map<String, List<String>> test_map_key) {
        this.test_map_key = test_map_key;
    }
}

调用mapper.writeValueAsString()序列化上述实体类实例,即可得到你期望的JSON结构:

{
  "name": "test_name",
  "test_map_key": {
    "key_map": ["value1", "value2"]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:45:35