java - 循环遍历嵌套的 Retrofit JSON 结果

标签 java android retrofit

我有一个如下所示的 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 17)。

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/

相关文章:

android - 使用 Retrofit 自定义错误处理

java - Retrofit.RetrofitError 请求网络执行过程中出现异常 : null

java - 正则表达式和自定义标签

Android 操作栏可检查菜单项无法正常工作/显示?

android - 从 Play 商店升级时,我的应用程序在版本上崩溃,并抛出资源未找到

android - MDPI、HDPI、XHDPI 和 XXHDPI 的不同 APK

java - 应用程序无法使用类路径启动.../负匹配

Java:JPanel 中的垂直对齐

java - 如何重用电子邮件的 JIRA 速度模板?

android - RecyclerView 不显示项目