如何从包含自己的数组的对象数组中获取n条记录



我想要n个数字,这意味着我对ArrayList的最后一条记录,但问题是我的ArrayList是自定义POJO类的,它包含自己的数组,这就是为什么我无法确定ArrayList包含多少条记录的原因

请在下面检查我正在从中创建 POJO 类的 JSON

{
  "data": [
    {
      "id": "7",
      "name": "Grand Father Name",
      "parent_id": "0",
      "relation_type": "grand-father",
      "children": [
      ]
    },
    {
      "id": "8",
      "name": "Grand Mother Name",
      "parent_id": "0",
      "relation_type": "grand-mother",
      "children": [
        {
          "id": "9",
          "name": "Father Name",
          "parent_id": "8",
          "relation_type": "father",
          "children": [
            {
              "id": "11",
              "name": "My Name",
              "parent_id": "9",
              "relation_type": "self",
              "children": [
              ]
            }
          ]
        },
        {
          "id": "10",
          "name": "Mother Name",
          "parent_id": "8",
          "relation_type": "mother",
          "children": [
          ]
        }
      ]
    }
  ]
}

波乔类

public class Tree {
    @SerializedName("data")
    @Expose
    public ArrayList<Child> data = null;
    public class Child {
        @SerializedName("family_id")
        @Expose
        public int family_id;
        @SerializedName("name")
        @Expose
        public String name;
        @SerializedName("relation_type")
        @Expose
        public String relation_type;
        @SerializedName("parent_id")
        @Expose
        public int parentId;
        @SerializedName("children")
        @Expose
        public List<Child> children = null;
        public int getId() {
            return family_id;
        }
        public void setId(int id) {
            this.family_id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getParentId() {
            return parentId;
        }
        public void setParentId(int parentId) {
            this.parentId = parentId;
        }
        public List<Child> getChildren() {
            return children;
        }
        public void setChildren(List<Child> children) {
            this.children = children;
        }
    }
}

如您所见,子类包含自己的列表,因此我无法确定此列表将包含多少条记录

希望它能解决我的问题,任何帮助将不胜感激。提前致谢

您可以递归执行此操作:

ArrayList<Child> list = new ArrayList<>(); //this is the list where you want to fill all children
void fillRecursively(ArrayList<Child> root){
 List<Child> children = root.getChildren();
 for(Child child : children){
   if(child.getChildren().size()!=0){
    fillRecursively(child);
   }else{
   list.add(child);
   }
 }
}
}

另外,不要忘记将根节点添加到列表中。

list.add(root); //at the beginning

最新更新