Gabriel Bergamo Gabriel Bergamo - 6 months ago 132
iOS Question

NSJSONSerialization.JSONObjectWithData Returns nil

[
{
"_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

Rob Rob
Answer

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