我有一个快速的应用程序,可以调用 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
我尝试按照此处的示例进行操作:How to parse JSON in Swift using NSURLSession
但是收到错误“无法解析的标识符'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.
}
}
关于ios - 如何将 NSData 更改为 NSDictionary 或 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37832022/