Swift:无法序列化Json响应

时间:2016-06-15 22:14:42

标签: swift nsurlsession nsurl nsjsonserialization nsmutableurlrequest

我正在使用会话发出http请求。这是我的代码:

let task = session.dataTaskWithRequest(request){
    (data, response, error) -> Void in
    if error != nil {
        print(error?.description)
    } else {
        do {
            print("data recived : \(data)")
             let jsonContent = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions(rawValue: 0))
            print("json content: \(jsonContent)")
        }catch{

        }
    }
}
task.resume()

当我打印数据回复时,我得到了这个:

data recived : Optional(<OS_dispatch_data: data[0x1245c9d60] = { composite, size = 41479, num_records = 3 record[0] = { from = 0, length = 9580, data_object = 0x124584720 }, record[1] = { from = 0, length = 10846, data_object = 0x1245c9a00 }, record[2] = { from = 0, length = 21053, data_object = 0x1245c9f60 }, }>)

你们中任何人都知道NSJSONSerialization不起作用吗?

我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:-1)

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(URL, completionHandler: {(data, reponse, error) in

let jsonResults : AnyObject

do {
        jsonResults = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
      // success ...
  } 
 catch let error as NSError {
      // failure
      print("Fetch failed: \(error.localizedDescription)")
    }

})

task.resume()