Java 循环遍历嵌套JSON数组
我有一个JSON响应,如下所示:Java 循环遍历嵌套JSON数组,java,json,Java,Json,我有一个JSON响应,如下所示: { "1":{ "id":"1", "user_id":"1", "children":[ { "id":"2", "user_id":"2", "children":[ { "id":"3",
{
"1":{
"id":"1",
"user_id":"1",
"children":[
{
"id":"2",
"user_id":"2",
"children":[
{
"id":"3",
"user_id":"3",
"children":[
{
"id":"4",
"user_id":"2",
"children":[
]
}
]
},
{
"id":"5",
"user_id":"1",
"children":[
]
}
]
},
{
"id":"6",
"user_id":"2",
"children":[
]
}
]
},
"7":{
"id":"7",
"user_id":"2",
...
}
}
for (Post post : postResponse.getData()) {
//
}
如您所见,我有嵌套数组(子数组
)。我需要循环这个JSON响应,遍历每个嵌套数组,直到它运行到一个空的子数组中,然后后退一步继续处理其余的项
我为响应创建了一个模型类,因此我当前的代码如下所示:
{
"1":{
"id":"1",
"user_id":"1",
"children":[
{
"id":"2",
"user_id":"2",
"children":[
{
"id":"3",
"user_id":"3",
"children":[
{
"id":"4",
"user_id":"2",
"children":[
]
}
]
},
{
"id":"5",
"user_id":"1",
"children":[
]
}
]
},
{
"id":"6",
"user_id":"2",
"children":[
]
}
]
},
"7":{
"id":"7",
"user_id":"2",
...
}
}
for (Post post : postResponse.getData()) {
//
}
显然,它只遍历顶级项(在我的例子中,id1
和7
)
我怎样才能做到这一点?您需要一个递归函数
function iterateTree(object) {
if (!object) { //recursion stop criteria || you need to implement what your stop criteria is
return;
}
//doSomthingWithObject();
iterateTree(object.children);
}
我相信您已经了解了如何在java中使用它 有什么理由不使用Jackson并在Person
课堂上列出孩子们的名单吗?我打赌周围有十几个重复的问题…请发布更多您尝试过的代码。是否有助于扩展帮助