I have JSON like below
{
"name" : "sahal",
"address" : [
{
"state" : "FL"
},
{
"country" : "FL",
"city" : {
"type" : "municipality",
"value" : "California City"
}
},
{
"pin" : "87876"
}
]
}
None of the key:value is constant. Name can change any time. And some time name comes like FirstName.
I tried with @JsonAnySetter and @JsonNode. These works with only one hierarchy
Any other way I can do this and reuse it for other JSON structure without writing the Pojo for each 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 :

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