Note that Jackson does not use java.
Jackson is a solid and mature JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON response objects with a lot of flexibility.
Jackson allows you to read JSON into a tree model: Java objects that represent JSON objects, arrays and values. These objects are called things like JsonNode or JsonArray and are provided by Jackson.
@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
.
There is an an open issue in the Jackson project to allow support for @JsonUnwrapped
on maps. It is currently tagged as targeted for the 2.13 release, so it looks to be in the near-term feature roadmap.
Until this feature is supported, the workaround about using @JsonAnySetter
/@JsonAnyGetter
proposed in another answer appears to be the way to go, and is in fact a suggested approach by the Jackson project author in the open issue:
as per this:
http://www.cowtowncoder.com/blog/archives/2011/07/entry_458.html
one can use @JsonAnyGetter/setter to do something possibly similar. One missing pieces is that currently one must have getter (can't use it on Map filed), but that should be easy enough to address.
@JsonAnySetter
public void add(String key, String value) {
map.put(key, value);
}
@JsonAnyGetter
public Map<String,String> getMap() {
return map;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With