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

使用com.fasterxml.jackson.databind的ObjectMapper能否提取Map值并无额外标签转JSON?

解决Jackson中Map属性与字段平级输出的问题

当然可以实现这个需求!Jackson专门提供了注解来处理这种场景,不用写复杂的自定义序列化逻辑,最简洁的方式就是用@JsonAnyGetter注解。

具体实现步骤

只需要在你的LoginInfoJSON类中,给properties对应的getter方法加上@JsonAnyGetter注解即可:

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import java.util.HashMap;
import java.util.Map;

public class LoginInfoJSON {
    private Map<String, Object> properties = new HashMap<>();
    private String username;
    private String password;

    // 构造器
    public LoginInfoJSON() {}

    // username和password的getter/setter
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }

    // 关键:添加@JsonAnyGetter注解
    @JsonAnyGetter
    public Map<String, Object> getProperties() {
        return properties;
    }

    // 可选:如果需要支持反序列化(从JSON转回对象),添加@JsonAnySetter
    @JsonAnySetter
    public void addProperty(String key, Object value) {
        properties.put(key, value);
    }
}

注解作用说明

  • @JsonAnyGetter:告诉Jackson,把这个方法返回的Map里的所有键值对,直接作为当前对象的顶级属性输出,不再嵌套在properties这个外层标签下。
  • @JsonAnySetter(可选):如果需要将平级结构的JSON反序列化为LoginInfoJSON对象,这个注解会把所有未匹配到实体类字段的属性,自动存入properties Map中。

转换后的JSON效果

假设你设置了如下数据:

LoginInfoJSON info = new LoginInfoJSON();
info.setUsername("testUser");
info.setPassword("123456");
info.getProperties().put("numberTest", 22);
info.getProperties().put("array", new String[]{"John","Anna","Peter"});
info.getProperties().put("nullTest", null);
info.getProperties().put("boolTest", true);

用ObjectMapper转换后得到的JSON会是:

{
  "username": "testUser",
  "password": "123456",
  "numberTest": 22,
  "array": ["John","Anna","Peter"],
  "nullTest": null,
  "boolTest": true
}

完全符合你想要的平级输出效果,没有多余的properties外层标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:15:23