ios - SwiftyJson : Looping an array inside an array

标签 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

最佳答案

您已经演示了如何遍历 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/

相关文章:

ios - 如何在更改纹理后调整 Sprite 的大小

iphone - 测试 Facebook 原生 iOS 应用

javascript - 主干网触发了错误的路由器方法

javascript - 当json值发生变化时,如何重新加载jquery jqGrid中的数据?

swift - 无法以编程方式调整约束

Swift 实例属性与方法 : lowercased() vs capitalized

ios - 是否可以使用 swift 将 Ipod 库中的音乐保存到我的应用程序中?

ios - 导航栏标题怎么可能不只在一个特定 View 上居中对齐?

php - 为什么我不能将零设置为数组中的第一个键?

swift - 检查 File 是否存在于 Web 服务器上的最简单解决方案。 ( swift )