使用Swift 3进行JSON序列化 [英] JSON serialization with Swift 3
本文介绍了使用Swift 3进行JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过填充JSON数据数组来填充表.我正在使用下面的代码,但始终收到错误:
I am trying to to populate a table by filling an array from JSON data. I am using the code below but keep getting the error:
任何"类型没有下标成员
Type 'Any' has no subscript members
在以下代码行中
:
on the following lines of code:
self.tableData.append(jsonResult[i]["title"]! as! String)
self.tableImages.append(jsonResult[i]["image"]! as! String)
self.tableDesc.append(jsonResult[i]["description"]! as! String)
self.tableValidity.append(jsonResult[i]["validity"]! as! String)
我的代码:
let str3 = Int(str2!)!
let url = NSURL(string: "https://www.*****.php")!
let task = URLSession.shared.dataTask(with: url as URL) { (data, response, error) -> Void in
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
print(str3)
var i = 0
while i < str3 {
print(jsonResult[i]["title"]! as!String)
print(jsonResult[i]["image"]! as! String)
self.tableData.append(jsonResult[i]["title"]! as! String)
self.tableImages.append(jsonResult[i]["image"]! as! String)
self.tableDesc.append(jsonResult[i]["description"]! as! String)
self.tableValidity.append(jsonResult[i]["validity"]! as! String)
i = i + 1
}
} catch {
print("JSON serialization failed")
}
} else {
print("ERROR FOUND HERE")
}
DispatchQueue.main.async(execute: { () -> Void in
self.tableView.reloadData()
})
}
task.resume()
推荐答案
编译器不知道jsonResult
的类型,您必须说出它是什么,例如使用这样的可选绑定:
The compiler doesn't know the type of jsonResult
, you have to tell what it is, for example with optional binding like this:
if let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as? [[String:AnyObject]] {
}
在这里,我将JSON下放为字典数组.在此if let
中使用您的循环,它应该可以工作.
Here I downcast the JSON as an array of dictionaries. Use your loop inside this if let
and it should work.
这篇关于使用Swift 3进行JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文