Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSJSONSerialization.JSONObjectWithData Returns nil

Tags:

ios

swift

[
    {
        "_id": "557f27522afb79ce0112e6ab",
        "endereco": {
            "cep": "asdasd",
            "numero": "asdasd"
        },
        "categories": [],
        "name": "teste",
        "hashtag": "teste"
    }
]

Returns nil without error :

var json = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error: &erro) as? NSDictionary
like image 319
Gabriel Bergamo Avatar asked Mar 02 '26 13:03

Gabriel Bergamo


1 Answers

It's returning nil without error because it's not the JSON parsing that's failing. It's failing because of the conditional type cast of the resulting object as a dictionary. That JSON doesn't represent a dictionary: It's an array with one item (which happens to be a dictionary). The outer [ and ] indicate an array. So, when you parse this, you want to cast it as a NSArray.

For example, in Swift 1.2 you could:

if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSArray, let dictionary = json.firstObject as? NSDictionary {
    println(dictionary)
} else {
    println(error)
}

Or you could cast it as an array of dictionaries:

if let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? [[String: AnyObject]], let dictionary = json.first {
    println(dictionary)
} else {
    println(error)
}
like image 70
Rob Avatar answered Mar 05 '26 02:03

Rob