以下是一个遍历JSONObject并获取其更深层次的子孙值的示例代码:
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonTraversalExample {
public static void traverseJSONObject(JSONObject jsonObject) {
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
// 递归遍历子JSONObject
traverseJSONObject((JSONObject) value);
} else if (value instanceof JSONArray) {
// 遍历JSONArray中的元素
traverseJSONArray((JSONArray) value);
} else {
// 输出键值对
System.out.println(key + " : " + value);
}
}
}
public static void traverseJSONArray(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
Object value = jsonArray.get(i);
if (value instanceof JSONObject) {
// 递归遍历子JSONObject
traverseJSONObject((JSONObject) value);
} else if (value instanceof JSONArray) {
// 递归遍历子JSONArray
traverseJSONArray((JSONArray) value);
} else {
// 输出数组元素
System.out.println(value);
}
}
}
public static void main(String[] args) {
// 示例JSONObject
String jsonString = "{\"key1\":\"value1\",\"key2\":{\"key3\":\"value3\",\"key4\":[1,2,3]},\"key5\":[{\"key6\":\"value6\"}]}";
JSONObject jsonObject = new JSONObject(jsonString);
// 遍历JSONObject
traverseJSONObject(jsonObject);
}
}
该示例代码使用递归方法来遍历JSONObject和JSONArray,在遍历过程中判断元素的类型,如果是JSONObject或JSONArray则再次递归遍历。对于非JSONObject和JSONArray类型的元素,直接输出。运行以上代码,输出结果如下:
key1 : value1
key3 : value3
1
2
3
value6