我的豆子看起来像这样:

class MyBean {

    private @JsonUnwrapped HashMap<String, String> map = new HashMap<String, String>();

    private String name;

    public HashMap<String, String> getMap() {
        return map;
    }

    public void setMap(HashMap<String, String> map) {
        this.map = map;
    }

    public String getName() {
        return name;
    }

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

当我使用以下代码序列化bean时:

MyBean bean = new MyBean();
HashMap<String, String> map = new HashMap<String, String>();;
map.put("key1", "value1");
map.put("key2", "value2");
bean.setMap(map);
bean.setName("suren");
ObjectMapper mapper = new ObjectMapper();
System.out.println("\n"+mapper.writeValueAsString(bean));

I'm getting result like this:

{"map":{"key2":"value2","key1":"value1"},"name":"suren"}

but

{"key2":"value2","key1":"value1","name":"suren"}

预计每JacksonFeatureUnwrapping documentation人.为什么我得不到展开的结果?

推荐答案

@JsonUnwrapped doesn't work for maps, only for proper POJOs with getters and setters. For maps, You should use @JsonAnyGetter and @JsonAnySetter (available in jackson version >= 1.6).

In your case, try this:

@JsonAnySetter 
public void add(String key, String value) {
    map.put(key, value);
}

@JsonAnyGetter
public Map<String,String> getMap() {
    return map;
}

That way, you can also directly add properties to the map, like add('abc','xyz') will add a new key abc to the map with value xyz.

Json相关问答推荐

嵌套自定义解组

如何使用JQ有条件 Select 值

使用单元和非单元版本反序列化Rust中的枚举,而无需编写自定义反序列化程序

JQ如何获取特定子元素的所有父母

Flutter -控制器问题-JSON API

使用JQ在数组中 Select 第一个具有匹配项的项

将 REST API - json 输出转换为表 Power BI

使用 jq 重新格式化 JSON 输出

未知的META规范,无法验证.[规范v1.0.1]

jq :遍历 json 并在键存在时检索集合

使用 jq 和脚本 bash 映射两个 json

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

JSON 字段的多个名称

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

如何使用 boost::json::value 调用无参数函数

如何使用 ConfigurationBuilder 解析现有的 json 字符串(不是文件)

为什么在测试 RSPEC 时 JBuilder 不返回 JSON 中的响应正文

如何一次加载无限滚动中的所有条目以解析python中的HTML

如何获取json格式的KendoGrid显示数据?

使用杰克逊创建一个 json 对象