Search code examples
swiftnsjsonserialization

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.


Solution

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