加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用Swift 3解析JSON

发布时间:2020-12-14 05:34:06 所属栏目:百科 来源:网络整理
导读:我有这个我希望在 Swift 3中使用的json数据.我正在学习Swift并构建一个非常基本的应用程序,它显示来自JSON的tableUIView中的项目列表. { "expertPainPanels" : [ { "name": "User A","organization": "Company A" },{ "name": "User B","organization": "Com
我有这个我希望在 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] {

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读