Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I push jackson-mapped @JsonProperties to the "top level"?

Tags:

java

json

jackson

Given a Java class like the following:

class MyClass {

    String value;

    Map<String,Object> map;

    @JsonProperty("value")
    public String getValue() {
        return value;
    }

    @JsonProperty("map")
    public Map<String,Object> getMap {
        return map;
    }
}

Jackson will convert to JSON like so:

{
    "value": "abc",
    "map": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    }

}

What I would like instead is to "flatten" the map attribute somehow so its contents appears at the "top-level" of the JSON structure like this:

{
    "value": "abc",
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
}

Is that possible declaratively through any combinations of Jackson annotations?

(This is a simplification of my actual problem, so I am not looking for an answer like "write your own custom MyClass serializer." In reality, this class must work with custom ObjectMappers in a scenario out of my direct control.)

like image 802
Brian Kent Avatar asked Feb 12 '14 23:02

Brian Kent


1 Answers

you can try @JsonUnwrapped

As per link, this is supposed to remove a layer of wrapping.

(Jackson 1.9+) @JsonUnwrapped (property; i.e method, field) Properties that are marked with this annotation will be "unwrapped", that is, properties that would normally be written as properties of a child JSON Object are instead added as properties of enclosing JSON Object.

like image 84
ezhilxor Avatar answered Oct 24 '22 22:10

ezhilxor