使用Swift 3解析JSON

use*_*605 2 json swift3

我有这个我希望在Swift 3中使用的json数据.我正在学习Swift并构建一个非常基本的应用程序,它显示来自JSON的tableUIView中的项目列表.

{
  "expertPainPanels" : [
     {
       "name": "User A",
       "organization": "Company A"
     },
     {
       "name": "User B",
       "organization": "Company B"
     }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用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)")
        }
     }
Run Code Online (Sandbox Code Playgroud)

它在Swift 2中运行良好.我更新了Swift 3,它破坏了代码.我读过几篇SO,但我仍然很难理解它.我在Swift 3中应用了一些建议,包括JSON解析,但我仍然无法解决我得到的错误.

And*_*nez 7

从Swift 3开始,你需要尽早进行演员表演.

这一行:

let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments)
Run Code Online (Sandbox Code Playgroud)

应该成为这样的:

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? [String : AnyObject]
Run Code Online (Sandbox Code Playgroud)

这是因为JSONSerialization现在返回Any,这不会为[]运算符实现变体.确保您安全地展开演员,并采取常见措施,以确保您不会崩溃你的程序.

编辑:您的代码应该或多或少看起来像这样.

let data = Data()
let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String : AnyObject]
if let experts = json["expertPainPanels"] as? [String: AnyObject] {
Run Code Online (Sandbox Code Playgroud)