Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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

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:

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("
"+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 JacksonFeatureUnwrapping documentation. Why am I not getting the unwrapped result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...