循环嵌套的Retrofit JSON结果

时间:2015-12-31 20:46:01

标签: 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()) {
      //
    }
  }
}

这显然只会遍历顶级项目(在我的情况下为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;
  }
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

你可以试试递归......

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() );
  }
}

当然,有了这个,你就无法得到你想要的顺序,所以你可能想要稍微使用那个解决方案。但它可能会让你知道如何开始......