如何将NSDATA更改为nsdictionary或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

我试图在此处遵循以下示例:如何使用nsurlsession在Swift中解析JSON

,但获取错误"未解决的标识符'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.
              }
}

最新更新