【问题标题】:SwiftyJson: Looping an array inside an arraySwiftyJson:在数组内循环数组
【发布时间】:2016-07-30 15:09:30
【问题描述】:

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

{
"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

【问题讨论】:

    标签: ios json swift xcode swifty-json


    【解决方案1】:

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

    【讨论】:

    • 工作就像一个魅力!这两个提要数组起初确实让我感到困惑,但你的回答让我明白了!
    • 无论如何我可以在内部项目循环中打印 id 和用户名吗?问题是当有多个内部提要时,它会减轻存储空间
    • 只需将print(item["id"].stringValue) 行移到内部循环中
    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 2019-02-13
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2016-11-09
    相关资源
    最近更新 更多