SwiftyJson:在数组中循环一个数组

时间:2016-07-30 15:09:31

标签: ios json swift xcode swifty-json

我正在尝试遍历数组中的数组。第一个循环很简单,但我在循环其中的第二个数组时遇到了麻烦。欢迎任何建议!

{
"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”以及相应的like_count和comment_count

1 个答案:

答案 0 :(得分:3)

您已经演示了如何遍历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数组中的第一项,请将内部替换为lop:

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