gpt4 book ai didi

ios - Swift 3 循环 JSON 数据

转载 作者:可可西里 更新时间:2023-11-01 02:16:29 26 4
gpt4 key购买 nike

我正在尝试遍历一个 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"
}]
}
}

最佳答案

您应该使用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

关于ios - Swift 3 循环 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38023737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com