SwiftyJson:在数组内部循环另一个数组

3
我试图循环遍历一个数组内部的另一个数组。第一个循环很容易,但我无法循环遍历其中的第二个数组。欢迎提供任何建议!
{
"feeds": [
{
  "id": 4,
  "username": "andre gomes",
  "feeds": [
    {
      "message": "I am user 4",
      "like_count": 0,
      "comment_count": 0
    }
  ]
},
{
  "id": 5,
  "username": "renato sanchez",
  "feeds": [
    {
      "message": "I am user 5",
      "like_count": 0,
      "comment_count": 0
    },
    {
      "message": "I am user 5-2",
      "like_count": 0,
      "comment_count": 0
    }
  ]
}
]
}

您看到了,我无法到达消息字段等。

这是我的 swiftyjson 代码。

let json = JSON(data: data!)

for item in json["feeds"].arrayValue {

print(item["id"].stringValue)
print(item["username"].stringValue)
print(item["feeds"][0]["message"])
print(item["feeds"][0]["like_count"])
print(item["feeds"][0]["comment_count"])

}

我得到的输出是:
4
andre gomes
I am user 4
0
0
5
renato sanchez
I am user 5
0
0

如您所见,我无法获取消息“我是用户5-2”,以及相应的点赞数和评论数。

1个回答

4

您已经演示了如何遍历JSON数组,因此您只需要再次使用内部的feeds进行遍历:

let json = JSON(data: data!)

for item in json["feeds"].arrayValue {

    print(item["id"].stringValue)
    print(item["username"].stringValue)

    for innerItem in item["feeds"].arrayValue {
        print(innerItem["message"])
        print(innerItem["like_count"])
        print(innerItem["comment_count"])
    }

}

如果你只想要内部feeds数组中的第一个项目,可以用以下代码替换内部的for循环:

print(item["feeds"].arrayValue[0]["message"])
print(item["feeds"].arrayValue[0]["like_count"])
print(item["feeds"].arrayValue[0]["comment_count"])

运行得非常好!一开始两个 feeds 数组确实让我感到困惑,但是你的答案解决了我的问题! - Ameya Vichare
有没有办法在内部循环中打印id和用户名?问题是当存在多个内部feed时,这将减轻存储的负担。 - Ameya Vichare
1
只需将print(item["id"].stringValue)行移动到内部循环即可。 - Code Different

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接