I want the ability to return Json's keys and values, especially nested ones. The nested keys will have their parent key as a prefix. Example: This Json:
{
"name": "Josh",
"id": 23435,
"Group": {
"class": "ranger",
"level": 60
}
}
Keys will be in this format:
name, id, Group.class, Group.level
I have a recursive function that does it, and also returns the values as pairs in a map, but the problem happens with arrays within the Json. How can I support handling arrays inside the json?
This is the method:
public static void findKeysAndValues(Object object, String key,Map <String, String> finalKeys) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
jsonObject.keySet().forEach(childKey -> {
findKeysAndValues(jsonObject.get(childKey), key != null ? key + "_" + childKey : childKey, finalKeys); //Also add requestPayLoad_ as parent key
});
} else if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
finalKeys.put(key,((JSONArray) object).toString()); //Also add requestPayLoad_ as parent key
IntStream.range(0, jsonArray.length())
.mapToObj(jsonArray::get)
.forEach(jsonObject -> findKeysAndValues(jsonObject, key, finalKeys));
}
else{
finalKeys.put(key,object.toString());
}
}
And that's how you call it in the first time:
Map<String,String> KeysAndValues = new HashMap<>();
findKeysAndValues(jsonObject,null,KeysAndValues);
If there is a cleaner way also to get the results more correctly, and in my desired format, I'd love to hear more. *The original recursive function, before my enhancement, comes from this question: Retrieving all the keys in a nested json in java