【问题标题】:Swift 3 looping JSON dataSwift 3 循环 JSON 数据
【发布时间】:2016-06-25 00:13:25
【问题描述】:

我正在尝试循环通过 JSON 数组将数据发送到结构。

这是我使用 SwiftyJSON 返回 JSON 对象的代码:

performAPICall() {
    json in
    if(json != nil){
    print("Here is the JSON:")
    print(json["content"]["clients"])

        let clients = json["content"]["clients"]
        for client in clients {
            var thisClient = Client()
            thisClient.id = client["id"].string
            thisClient.desc = client["desc"].string
            thisClient.name = client["name"].string
            self.clientArray.append(thisClient)
    }
    self.tableView.reloadData()
    } else {
        print("Something went very wrong..,")
    }
}

我不太确定为什么在三个字符串上出现“没有下标”错误。

任何帮助表示赞赏,谢谢。

编辑:这是 JSON 的示例

{
    "content": {
        "clients": [{
            "group": "client",
            "id": "group_8oefXvIRV4",
            "name": "John Doe",
            "desc": "John's group."
        }, {
            "group": "client",
            "id": "group_hVqIc1eEsZ",
            "name": "Demo Client One",
            "desc": "Demo Client One's description! "
        }, {
            "group": "client",
            "id": "group_Yb0vvlscci",
            "name": "Demo Client Two",
            "desc": "This is Demo Client Two's group"
        }]
    }
}

【问题讨论】:

  • 你能发布 JSON 对象吗?
  • 我已将其添加到问题中。
  • 不幸的是不是这样,我忘了包括顶级“顶级”级别,但如果我只是打印(json),它就在那里。
  • 使用 SwiftyJSON 来下载,就是那个出来的 JSON。

标签: ios swift for-loop struct swifty-json


【解决方案1】:

您应该使用array 方法。因此,您的线路

let clients = json["content"]["clients"]

应该使用array(并安全地打开它):

guard let clients = json["content"]["clients"].array else {
    print("didn't find content/clients")
    return
}

// proceed with `for` loop here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    相关资源
    最近更新 更多