代码
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnGirisYap(_ sender: Any) {
let url = NSURL(string: "http://www.kerimcaglar.com/yemek-tarifi")!
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) as! [String:AnyObject]
//print (jsonResult)
self.txtGirisKullaniciAdi.text = jsonResult["malzemeler"] as! NSString as String
} catch {
print("JSON serialization failed")
}
} else {
print("ERROR FOUND HERE")
}
}
task.resume()
}
}
你能帮忙解决这个问题吗?
答案 0 :(得分:0)
错误消息清楚地告诉您反序列化对象是数组而不是字典。
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as! [[String:Any]]
for item in jsonResult {
print(item["malzemeler"] as! String) // cast directly to String
}
注意:
[String:Any]
。mutableContainers
选项在Swift中无用。