我有要在Swift3中使用的json数据。我正在学习Swift,并正在构建一个非常基本的应用程序,该应用程序显示来自JSON的tableUIView中的项目列表。
{ "expertPainPanels" : [ { "name": "User A", "organization": "Company A" }, { "name": "User B", "organization": "Company B" } ] }
我正在尝试使用Swift 3获取此数据。
if (statusCode == 200) { do{ let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments) // [[String:AnyObject]] /* If I do this: let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any] if let experts = json?["expertPainPanels"] as! [String: Any] { I get "Initializer for conditional binding must have Optional type, not '[String: Any]'" */ // Type 'Any' has no subscript members. if let experts = json["expertPainPanels"] as? [String: AnyObject] { for expert in experts { let name = expert["name"] as? String let organization = expert["organization"] as? String let expertPainPanel = ExpertPainPanel(name: name, organization: organization)! self.expertPainPanels += [expertPainPanel] self.tableView.reloadData() self.removeLoadingScreen() } } }catch { print("Error with Json: \(error)") } }
在Swift 2中运行正常。我更新到Swift 3,这破坏了代码。我读了几篇SO,但是我仍然很难理解它。我应用了一些建议,包括Swift 3中的JSON Parsing,但是我仍然无法解决出现的错误。
从Swift 3开始,您需要尽早进行投射。
这行:
let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments)
应该变成这个:
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? [String : AnyObject]
这是因为JSONSerialization现在返回Any,它没有为[]运算符实现变体。确保安全地打开演员表,并采取常见措施以确保程序不会崩溃。
Any
[]
编辑:您的代码应该或多或少看起来像这样。
let data = Data() let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String : AnyObject] if let experts = json["expertPainPanels"] as? [String: AnyObject] {