Search code examples
iosjsonswiftnsdata

How to change an NSData to an NSDictionary or JSON


I have a swift app that calls api and recieves back a 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

My get() function is defined as such:

func get(path: String) -> Request {

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

EDIT 2

I am using

import UIKit
import Alamofire
import SwiftyJSON

EDIT 3

I attempted to follow the example here:How to parse JSON in Swift using NSURLSession

But get the error "unresolved identifier 'JSONSerialization'"

EDIT 4 / probable answer

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. I was led to this by the comment suggesting to use swiftJSON


Solution

  • A very standard way to convert to JSON from NSData, feel free to ask a question

      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.
                  }
    }