Gabriel Bergamo
Gabriel Bergamo

Reputation: 33

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

Upvotes: 3

Views: 4251

Answers (2)

P.nima
P.nima

Reputation: 1

Calling isValidJSONObject: or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.

isValidJSONObject(_:) Returns a Boolean value that indicates whether a given object can be converted to JSON data.

Declaration SWIFT class func isValidJSONObject(_ obj: AnyObject) -> Bool Parameters obj The object to test. Return Value true if obj can be converted to JSON data, otherwise false.

Discussion Availability Available in iOS 5.0 and later.

Upvotes: 0

Rob
Rob

Reputation: 437442

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

Upvotes: 4

Related Questions