尝试使用 Android 中的嵌套列表整理 Json

Trying to sort out Json with Nested Lists in Android

我有Json我正在接收和解析好的,但我现在有点不知道如何处理它。

"success": true,
"data": {
"endingIndex": 1,
"segmentCount": 2,
"startingIndex": 0,
"totalCount": 2,
"comments": [
  {
    "childCount": 1,
    "content": "This is a root Comment",
    "id": 2342246,
    "parentID": null,
    "submissionID": 623234,
    "children": {
      "endingIndex": 0,
      "segmentCount": 1,
      "startingIndex": 0,
      "totalCount": 1,
      "comments": [
        {
          "childCount": 1,
          "content": "This is second Level Comment",
          "id": 2342275,
          "parentID": 2342246,
          "submissionID": 623234,
          "children": {
            "endingIndex": 0,
            "segmentCount": 1,
            "startingIndex": 0,
            "totalCount": 1,
            "comments": [
              {
                "childCount": 0,
                "content": "This is a third Level Comment",
                "id": 2342310,
                "parentID": 2342246,
                "submissionID": 623234,
                "children": null
              }
            ]
          }
        }
      ]
    }
  },
  {
    "childCount": 0,
    "content": "This is first Level Comment too!",
    "id": 2342298,
    "parentID": null,
    "submissionID": 623234,
    "children": null
  }
]

我建模了两个对象:

public class Segment{ 

private List<Comment> comments;
private int endingIndex;
private int segmentCount;
private int startingIndex;
private int totalCount;

//getters...
    }    

public class Comment{

private int childCount;
private String content;
private int id;
private int parentID;
private Segment children;

//getters...
}

我遇到的问题是试图处理数据。我想做一个交错评论的列表,但是想到列表的列表我的脑子有点烧焦了。

我从我的 Api 请求

收到根段
CommentSegment fetchedCommentList = new CommentSegment(api);
//this should contain all the info

然后我想我需要里面的评论列表

List<Comment> rootComments = new ArrayList<>;
for(Comment comment : fetchedCommentList.getComments()){
    rootComments.add(new Comment(comment));
}
///This should get me the first level, but how to I get the additional 
// levels and get it ordered correctly?

现在我的大脑正在爆炸,我该何去何从?

您可以使用队列,然后像这样沿着数据树向下移动:

private List<Comment> treeQueue(Segment parent) {
    List<Comment> comments = new List<Comment>();
    Queue queue = new LinkedList();


    for (Comment comment : parent.getcomments()) {

        queue.add(comment);

        while(!queue.isEmpty()) {
            Comment node = (Comment)queue.remove();
            comments.add(comment);
            if (node.childCount > 0) {
                for (Comment child : ((Segment)node.getchildren()).getcomments()) {
                    queue.add(child);
                }
            }
        }
    }

    return comments;
}