Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Serialization crashing in swift

I had been using the following line of code to parse JSON data in Objective-C, but the same in Swift crashes the app.

NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:_webData
                          options:kNilOptions
                          error:&error];

I tried using NSJSONReadingOptions.MutableContainers but doesn't seem to work. I have verified the validity of the JSON data obtained from the web server using various JSON validity checkers found online.

[EDIT] The swift code I am using is as follows:

let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

[UPDATE]

Using let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary solves the issue.

like image 380
Jeswin Avatar asked Jun 12 '14 15:06

Jeswin


2 Answers

The error Xcode is giving you isn't very helpful, but it looks like you need to declare your error variable a different way (more at Apple's documentation), and then make sure you handle the case of the dictionary coming back nil:

var error: AutoreleasingUnsafePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data,
        options:NSJSONReadingOptions.MutableContainers,
        error: error) as? NSDictionary
if jsonResult {
    // process jsonResult
} else {
    // couldn't load JSON, look at error
}
like image 193
Nate Cook Avatar answered Sep 18 '22 04:09

Nate Cook


All answers didn't work for me. This worked (21.01.2015 - Xcode 6.1.1 / iOS 8.1.2):

 var err: AutoreleasingUnsafeMutablePointer<NSError?> = nil

 var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:err) as NSDictionary

Found it here: Use of undeclared type AutoreleasingUnsafePointer Xcode 6 beta 6

like image 25
MB_iOSDeveloper Avatar answered Sep 18 '22 04:09

MB_iOSDeveloper