使用Swift 3解析JSON

前端之家收集整理的这篇文章主要介绍了使用Swift 3解析JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个我希望在 Swift 3中使用的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,但我仍然很难理解它.我应用了一些建议,包括JSON Parsing in Swift 3,但我仍然无法修复我得到的错误.

从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,它没有为[]运算符实现变体.确保您安全地展开演员,并采取常见措施,以确保您不会崩溃你的程序.

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

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

猜你在找的Swift相关文章