我正在尝试遍历数组中的数组。第一个循环很简单,但是我在循环第二个数组时遇到了麻烦。欢迎任何建议!
{
"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
}
]
}
]
}如您所见,我很难到达消息字段等。
这是我对金丝提斯的密码
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如您所见,我无法得到消息“I是用户5-2”以及相应的like_count和comment_count。
发布于 2016-07-30 15:21:33
您已经演示了如何循环使用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"])https://stackoverflow.com/questions/38675397
复制相似问题