Marco Schl
Marco Schl

Reputation: 337

JSONSerialization and EXC_BAD_ACCESS

I fetch some information from a MYSQL database with the help of a php service. At the end i push it through echo json_encode($resultArray) to my app. Now I have a problem with JSONSerialization and here is my code.

If ( urlData != nil ) {
        let res = response as NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            NSLog("Response ==> %@", responseData);

            var error: NSError?

            let jsonData2:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary

            let success:NSInteger = jsonData2.valueForKey("IdUser") as NSInteger
            ...

With this code i get an error message EXC_BAD_ACCESS in the line of NSJSONSerialization. Does anybody know why?

The responseDate have this example value:

[{"IdUser":"2","preName":"Max","lastName":"Muster"}]

Thanks in advance.

Upvotes: 2

Views: 953

Answers (2)

Rob
Rob

Reputation: 437592

Your JSON response is not a NSDictionary. It is an array. Now this array has one item, which is, itself, a dictionary. But you have to parse the array first:

let array = NSJSONSerialization.JSONObjectWithData(urlData!, options:nil, error: &error) as NSArray

If you want to get the dictionary, you grab the first item from the array:

let dictionary = array[0] as NSDictionary

And if you want the field value from IdUser, you grab that string value and then call integerValue:

let idUser = dictionary["IdUser"]?.integerValue

By the way, if it's at all possible that the response may deviate in its format, you may want to be careful with your parsing of the response, employing optional binding to gracefully handle the absence of the data in the format you expected, e.g.:

var error: NSError?
if let array = NSJSONSerialization.JSONObjectWithData(urlData!, options:nil, error: &error) as? [[String: AnyObject]] {
    if let dictionary = array.first {
        if let idUser = dictionary["IdUser"]?.integerValue {
            // `IdUser` definitely found; now check the value here
        }
    }
}

Upvotes: 1

Beslan Tularov
Beslan Tularov

Reputation: 3131

an easy way to parse json in swift use SwiftyJSON but if you do not want it, you can do so

if let jsonData2 = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)  as? AnyObject {

        }

but I strongly recommend to use SwiftyJSON

Upvotes: 0

Related Questions