我试图在一个数组中遍历一个数组。第一个循环很简单,但我无法循环遍历其中的第二个数组。欢迎提出任何建议!
{
"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
最佳答案
您已经演示了如何遍历 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 lop 替换为:
print(item["feeds"].arrayValue[0]["message"])
print(item["feeds"].arrayValue[0]["like_count"])
print(item["feeds"].arrayValue[0]["comment_count"])
关于ios - SwiftyJson : Looping an array inside an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38675397/