ios - 如何将 NSData 更改为 NSDictionary 或 JSON

标签 ios json swift nsdata

我有一个快速的应用程序,可以调用 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/

相关文章:

python - 将字符串输入 PostgreSQL 会导致单引号语法错误

java - 如何在 Java 中将 HTTP 请求主体转换为 JSON 对象

swift - 如何以正确的方式在 Swift 中调度函数?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

swift - 无法将项目附加到 CollectionView

ios - 检测在 UITableView 中按下了哪个 UIButton

json - 在 Ext.data 的上下文中,JsonStore 和 JsonReader 之间的基本区别是什么?

ios - 在 Swift 编程中将 urlpath 添加到 NSUrl 时得到 nil

iOS [Obj-C] 基于同一数据库中不同 MySQL 表中的匹配键的 segue

ios - 保留循环与父子构造