Swift 3 循环 JSON 数据
Swift 3 looping JSON data
我正在尝试遍历 JSON 数组,将数据发送到结构。
这是我的代码,它使用 SwiftyJSON 来 return 一个 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..,")
}
}
我不太清楚为什么在三个字符串上出现 "has no subscript" 错误。
感谢任何帮助,谢谢。
编辑: 这是 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
我正在尝试遍历 JSON 数组,将数据发送到结构。
这是我的代码,它使用 SwiftyJSON 来 return 一个 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..,")
}
}
我不太清楚为什么在三个字符串上出现 "has no subscript" 错误。
感谢任何帮助,谢谢。
编辑: 这是 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