我有一个如下所示的 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",
...
}
}
如您所见,我有嵌套数组( children
)。我需要循环遍历这个 JSON 响应,遍历每个嵌套数组,直到它遇到空 children
数组,然后后退一步继续处理其余项目。
我为响应创建了一个模型类,所以我当前的代码如下所示:
RestClient.getService().getParents(new Callback<ParentResponse>() {
@Override
public void success(ParentResponse parentData, Response response) {
for (Parent parent : parentData.getData()) {
//
}
}
}
这显然只迭代顶级项目(在我的例子中,id 1
和 7
)。
Parent
的型号类看起来像这样:
public class Parent {
private String id;
private String userId;
private List<Parent> parents = new ArrayList<Parent>();
// get/set for id and userId
public List<Parent> getParents() {
return parents;
}
public void setParents(List<Parent> parents) {
this.parents = parents;
}
}
我该怎么做?
最佳答案
你可以尝试递归...
protected void doSomething(Parent p) {
... some code here for all parents
if (p.getChildren().isEmpty()) {
... some code here for empty parents
} else {
for(Parent child : getChildren()) {
doSomething( child );
}
}
}
另一个简单的想法...
public void doSomething(Parent p) {
Queue<Parent> toGo = new LinkedList<Parent>(p.getChildren());
while(!toGo.isEmpty()) {
Parent toDo = toGo.poll();
// do something with the element, if you need to
toGo.addAll( toGo.getChildren() );
}
}
当然,这样您将无法获得您想要的排序,因此您可能想尝试一下该解决方案。但它可能会让您知道如何开始......
关于java - 循环遍历嵌套的 Retrofit JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551468/