Guillaume Nargeot
Guillaume Nargeot

Reputation: 11

Flattening of json to a map with Jackson

I am currently using the Jackson library to unmarshal json to pojos, using annotations.

The json tree that I would like to unmarshal is as follows:

{
    "key1":"value1",
    "key2":"value2",
    "key3":{
        "key31":{
            "key311":"value311",
            "key312":"value312",
            "key313":"value313"
        },
        "key32":"value32"
    },
    "key4":"value4",
    "key5":"value5",
    "key6":{
        "key61":"value61"
    }
}

I don't know the json structure in advance and would like to completely flatten it to a Map which content would be equivalent to:

Map<String, Object> outputMap = new HashMap<String, Object>();
outputMap.put("key1", "value1");
outputMap.put("key2", "value2");
outputMap.put("key311", "value311");
outputMap.put("key312", "value312");
outputMap.put("key313", "value313");
outputMap.put("key32", "value32");
outputMap.put("key4", "value4");
outputMap.put("key5", "value5");
outputMap.put("key61", "value61");

(note that keys "key3", "key31" and "key6" should be ignored)

Using the annotation @JsonAnySetter, I can create a function to populate the map with all top level atoms, but the method will also catch the node having children (when the value is a Map).

From that point, I can of course write myself the simple recursion over the children, but I would like this part to be handled automatically (in an elegant way) through the use of a facility from the library (annotation, configuration, etc.), and not have to write the recursion by myself.

Note: we assume there is not name clashing in the different level keys.

Upvotes: 1

Views: 2164

Answers (1)

StaxMan
StaxMan

Reputation: 116502

There is no annotation-based mechanism to do this that I know of, since @JsonUnwrapped which might be applicable is only usable with POJOs, not Maps. I guess you could file an enhancement request to ask @JsonUnwrapped to be extended to also handle Map case, although it seems only appicable for serialization (not sure how one could deserialize back).

Upvotes: 1

Related Questions