java如何遍历JSONObject的N个级别?
我想知道是否有人知道这个JSON模型的N个级别是否可以迭代,如果可以,如何迭代?我正在用JAVA做这件事,我可以访问Gson库
{
"description": "Name of the level",
"value": "Name of the value",
"cat": {
"description":"Name of the level",
"value": "Name of the value",
"cat": {
"description":"Name of the level",
"value": "Name of the value",
"cat": {
"description":"Name of the level",
"value": "Name of the value",
"cat" : {
"description":"Name of the level",
"value": "Name of the value",
"cat": null
}
}
}
}
}
我想做的是能够遍历这个JSON并检索每个级别的“描述”和“值”,而不知道有多少级别。在某些情况下,可能只有两个级别,而在其他情况下,可能多达10个级别
我在JAVA中尝试过这种方法:
Map<String, Object> map = gson.fromJson(jsonGeneric, new TypeToken<Map<String, Object>>() {}.getType());
map.forEach((x, y) -> System.out.println("key : " + x + " , value : " + y));
然而,这只会迭代第一个级别,我无法找到一种方法来调整代码以迭代多个级别,或者想出另一个解决方案
# 1 楼答案
感谢卡尔·希尔斯的评论,这让我走上了正确的道路。因此,我要寻找的最终代码如下: