Swift 2 - NSJSONSerialization.JSONObjectWithData处理错误

时间:2015-11-13 12:36:56

标签: ios json swift swift2

我有一个JSONParser,但不幸的是我无法将NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error)位调整为Swift 2.0,所以我收到错误:

  

Extra argument 'error' in call

我发现我可以通过do-try-catch实现这一点,但我无法弄清楚如何在我的情况下适应它。无论我尝试什么,只是抛出另一个错误。

class JSONParser {

  let json: AnyObject?
  var error: NSError?

  init(data: NSData){  // ~this chunk~
      self.json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error)
  }

  func array()->NSArray?{
      if let jsonResponse: AnyObject = self.json{
          return jsonResponse as? NSArray
      }
      return nil
  }

  func dictionary()->NSDictionary?{
      if let jsonResponse: AnyObject = self.json{
          return jsonResponse as? NSDictionary
      }
      return nil
  }
}

2 个答案:

答案 0 :(得分:11)

<强> swift3

NSJSONSerialization及其方法根据Swift Documents修改。

do {

    let JsonDict = try JSONSerialization.jsonObject(with: data, options: [])
    // you can now use t with the right type        
    if let dictFromJSON = JsonDict as? [String:String]
 {
        // use dictFromJSON
    }
} catch let error as NSError {
    print(error)
}

Swift2

   init(data: NSData){  // ~this chunk~
     do {
        self.json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String:AnyObject]

     } catch {
        print("error: \(error)")
        self.json = nil
     }
  }

了解更多信息tutorial1tutorial2

答案 1 :(得分:-2)

var dataSource = [AnyObject]()


do {  self.dataSource = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableLeaves) as! [AnyObject]
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}

if self.dataSource.count != 0 {

dispatch_async(dispatch_get_main_queue()) {
    self.sampleTableView.reloadData()
     }

      }