java using JSONObject to loop recursive through any jsondata
Solution 1:
JSONObject is like a java.util.Map, even if it does not implement the interface. You can take all keys and iterate through them even if you do not know them beforehand.
jsonObject.keySet()
This returns Set, consisting of the keys in the object. Now the recursive function:
private static void recursiveTraverse(String previousKey, JSONObject currentObject) {
//iterate each key
for (String currentKey : currentObject.keySet()) {
//build the next key
String nextKey = previousKey == null || previousKey.isEmpty() ? currentKey : previousKey + "-" + currentKey;
Object value = currentObject.get(currentKey);
if (value instanceof JSONObject) {
//if current value is object, call recursively with next key and value
recursiveTraverse(nextKey, (JSONObject) value);
} else if (value instanceof JSONArray) {
//if current value is array, iterate it
JSONArray array = (JSONArray) value;
for (int i = 0; i < array.length(); i++) {
Object object = array.get(i);
JSONObject jsonObject = (JSONObject) object;
//assuming current array member is object, call recursively with next key + index and current member
recursiveTraverse(nextKey + "-" + i, jsonObject);
//you might need to handle special case of current member being array
}
} else {
//value is neither object, nor array, so we print and this ends the recursion
System.out.println(nextKey + ", " + value);
}
}
}
Start traversing the object:
JSONObject jsonObject = new JSONObject(jsonString);
recursiveTraverse("", jsonObject);
It works good enough for most use cases, but as i have noted in comments in the code, it does not handle the case when current array element is another array. If your constraints allow this, you might have to implement recursive function for that . Something like this:
private static void recursiveHandleArray(String prevKey, JSONArray currentArray) {
//implement
}