Dynamic multi level hierarchy JSON to Java Pojo. Re-use for multiple projects
Consider to use JsonNode and fuse a hierarchy loop to extract all the keys and values dynamically regardless of patterns and relations and values,
public static void main(String[] args) throws JsonProcessingException {
//which hierarchy is your json object
JsonNode node = nodeGenerator(hierarchy);
JSONObject flat = new JSONObject();
node.fields().forEachRemaining(o -> {
if (!o.getValue().isContainerNode())
flat.put(o.getKey(), o.getValue());
else {
parser(o.getValue(), flat);
}
});
System.out.println(flat);
System.out.println(flat.get("type"));
}
public static JsonNode nodeGenerator(JSONObject input) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(input.toString());
}
public static void parser(JsonNode node, JSONObject flat) {
if (node.isArray()) {
ArrayNode array = node.deepCopy();
array.forEach(u ->
u.fields().forEachRemaining(o -> {
if (!o.getValue().isContainerNode())
flat.put(o.getKey(), o.getValue());
else {
parser(o.getValue(), flat);
}
}));
} else {
node.fields().forEachRemaining(o -> flat.put(o.getKey(), o.getValue()));
}
}
Which in your case extracted json will be as follow :