2016-11-24 168 views
1

代码斯威夫特3 JsonSerialization

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() 
    } 
} 

你能有帮助呢?

Error Screen Shoot

回答

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 
} 

注:

  • 未指定的JSON字典类型在夫特3是[String:Any]
  • mutableContainers选项在Swift中没用。