[英]How to change an NSData to an NSDictionary or JSON
I have a swift app that calls api and recieves back a JSON. 我有一个快速的应用程序,该应用程序调用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
}
And it prints out: 它打印出来:
...
data:
Optional(<7b227374 61747573 223a2234 3034222c 22657272 6f72223a 224e6f74 20466f75 6e64227d>)
fatal error: unexpectedly found nil while unwrapping an Optional value
I want to just print out the data is some readable form by converting to a dictionary. 我只想通过转换为字典来打印出某种可读形式的数据。
EDIT 1 编辑1
My get() function is defined as such: 我的get()函数定义如下:
func get(path: String) -> Request {
return self.get(path, data: NSDictionary())
}
EDIT 2 编辑2
I am using 我在用
import UIKit
import Alamofire
import SwiftyJSON
EDIT 3 编辑3
I attempted to follow the example here: How to parse JSON in Swift using NSURLSession 我尝试遵循以下示例: 如何使用NSURLSession在Swift中解析JSON
But get the error "unresolved identifier 'JSONSerialization'" 但是收到错误“未解析的标识符'JSONSerialization'”
EDIT 4 / probable answer 编辑4 /可能的答案
var newdata = JSON(data: dataExample!)
print(newdata)
outputted: 输出:
{
"status" : "404",
"error" : "Not Found"
}
I believe that this is a json and I am properly printing the readable data, so i believe this is the answer. 我相信这是一个json,并且我正在正确打印可读数据,所以我相信这就是答案。 I was led to this by the comment suggesting to use swiftJSON
建议使用swiftJSON的评论使我想到了这一点
A very standard way to convert to JSON from NSData, feel free to ask a question 从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.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.