为什么我无法使用 Jackson Java 库解包和序列化 Java 映射?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18043587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:01:15  来源:igfitidea点击:

Why I'm not able to unwrap and serialize a Java map using the Hymanson Java library?

javajsonHymanson

提问by Suren Raju

My bean looks like this:

我的豆子看起来像这样:

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;
    }
}

While I'm serializing the bean using the following code:

当我使用以下代码序列化 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"}

is expected per the HymansonFeatureUnwrapping documentation. Why am I not getting the unwrapped result?

根据HymansonFeatureUnwrapping 文档预计。为什么我没有得到解包的结果?

采纳答案by Hari Menon

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

@JsonUnwrapped不适用于地图,仅适用于具有 getter 和 setter 的适当 POJO。对于地图,您应该使用@JsonAnyGetter@JsonAnySetter(在 Hymanson 版本 >= 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 abcto the map with value xyz.

这样,您也可以直接向地图添加属性,例如add('abc','xyz')将一个新的键添加abc到地图中,并带有 value xyz

回答by M. Justin

There is currently an an open issueat the Hymanson project to allow support for @JsonUnwrappedon Maps. It is not tagged as being in the upcoming 2.10 or 3.x versions of Hymanson, so it does not look like it's on the near-term feature roadmap.

Hymanson 项目目前有一个未解决的问题,允许@JsonUnwrapped在地图上提供支持。它没有被标记为在即将到来的 2.10 或 3.x 版本的 Hymanson 中,所以它看起来不像是在近期的功能路线图上。

Until this feature is supported, the workaround about using @JsonAnySetter/@JsonAnyGetterproposed in another answerappears to be the way to go.

在支持此功能之前,在另一个答案中使用@JsonAnySetter/@JsonAnyGetter建议的解决方法似乎是可行的方法。