如何将 NSData 更改为 NSDictionary 或 JSON

How to change an NSData to an NSDictionary or JSON

我有一个 swift 应用程序调用 api 并收到 JSON。

    self.get(url).responseJSON { (response) -> Void in
        self.notify(FetchCompletion, response: response.response, result: response.result)
        print("response: ")
        print(response.response)
        print("data: ")
        let dataExample = response.data
        print(dataExample)
        let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObjectWithData(dataExample!)! as? NSDictionary
    }

然后打印出来:

...
data: 
Optional(<7b227374 61747573 223a2234 3034222c 22657272 6f72223a 224e6f74 20466f75 6e64227d>)
fatal error: unexpectedly found nil while unwrapping an Optional value

我只想通过转换为字典以某种可读形式打印出数据。

编辑 1

我的 get() 函数是这样定义的:

func get(path: String) -> Request {

    return self.get(path, data: NSDictionary())
}

编辑 2

我正在使用

import UIKit
import Alamofire
import SwiftyJSON

编辑 3

我尝试按照此处的示例进行操作:

但是得到错误"unresolved identifier 'JSONSerialization'"

编辑 4 / 可能的答案

var newdata = JSON(data: dataExample!)
print(newdata)

输出:

{
  "status" : "404",
  "error" : "Not Found"
}

我相信这是 json 并且我正在正确打印可读数据,所以我相信这就是答案。建议使用 swiftJSON

的评论让我想到了这一点

一个非常标准的从NSData转换为JSON的方法,欢迎提问

  self.get(url).responseJSON { (response) -> Void in
            self.notify(FetchCompletion, response: response.response, result: response.result)
            print("response: ")
            print(response.response)
            print("data: ")
            let dataExample = response.data
            print(dataExample)
    do {
           let dictionary = try NSJSONSerialization.JSONObjectWithData(dataExample!, options: NSJSONReadingOptions()) as! NSDictionary


        }
     catch {
        // catch error.
              }
}