【问题标题】:Swift to Swift 3 code conversions: Reading JSON filesSwift 到 Swift 3 代码转换:读取 JSON 文件
【发布时间】:2016-06-30 21:49:30
【问题描述】:

我有这个代码用于读取我正在尝试移动到 Swift 3 环境中的 JSON 文件。这里是:

do {
    let dictionary = try NSJSONSerialization.JSONObjectWithData(dataOK, options: NSJSONReadingOptions()) as AnyObject!
        dictionaryOK = (dictionary as! NSDictionary as? Dictionary <String, AnyObject>)!
  }
catch {
    print("Level file '\(filename)' is not valid JSON: \(error)")
    return nil
}

Xcode 给出了修复一些错误的建议(因为一些对象和类已被重命名),这会产生:

do {
    //Problem here: parameters don't match overrides
    let dictionary = try JSONSerialization.jsonObject(dataOK as Data, options: JSONSerialization.ReadingOptions()) as AnyObject!
    dictionaryOK = (dictionary as! NSDictionary as? Dictionary <String, AnyObject>)!
}
catch {
    print("Level file '\(filename)' is not valid JSON: \(error)")
    return nil
}

不匹配任何 jsonObjects 覆盖(它说)。我检查了文档,其中说 jsonObjects 的参数应该是:

class func jsonObject(with data: Data, 
           options opt: JSONSerialization.ReadingOptions = []) throws -> AnyObject

我做错了什么?

【问题讨论】:

    标签: json swift swift3 error-handling


    【解决方案1】:

    您的 Swift 2 代码一开始就非常冗长。

    试试这个:

    do {
        if let dictionaryOK = try JSONSerialization.jsonObject(with: dataOK, options: []) as? [String: AnyObject] {
            // parse JSON
        }
    } catch {
        print(error)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      相关资源
      最近更新 更多