Mapping unpredictable keys from JSON to POJO

jackson, json

Solution

If names are unpredictable, POJOs are not the way to go.

But you can use the Tree Model, like:

JsonNode root = objectMapper.readTree(jsonSource);

and access it as a logical tree. Also, if you do want to convert the tree (or any of sub-trees, as identified by node that is the root of sub-tree), you can do:

MyPOJO pojo = objectMapper.treeToValue(node, MyPOJO.class);

and back to tree

JsonNode node = objectMapper.valueToTree(pojo);

Problem

I am using the Jackson JSON library to map JSON streams into POJO's. My JSON's keys have unpredictable names. i.e ``` { "Random_ID": { "Another_Random_ID": { "some_key": "value" "some_key1": "value1" } } ... } ``` I would like to map this request to a POJO (with the same structure), however the mapper will fail since there is no such setXXX (where XXX is a random_id - since i cannot predict the name). What would be the best way to map this request to the corresponding object without manually parsing it with createJsonParser.

Original source