NSJSONSerialization.JSONObjectWithData Returns nil

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

      

Returns zero with no errors:

var json = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error: &erro) as? NSDictionary

      

+3


source to share


2 answers


It returns nil

without error because it is not JSON parsing which is failing. It doesn't work due to the conditional type of casting the resulting object as a dictionary. This JSON does not represent a dictionary: it is an array with one element (which turns out to be a dictionary). External [

and ]

indicate an array. So when you parse it, you want to use it like NSArray

.

For example, in Swift 1.2, you can:

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 can use it like 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)
}

      

+4


source


Calling isValidJSONObject: or attempting to convert are the final ways to determine if a given object can be converted to JSON data.

isValidJSONObject (_ :) Returns a Boolean value indicating whether this object can be converted to JSON data.



SWIFT declaration class func isValidJSONObject (_ obj: AnyObject) β†’ Bool OBJ parameters Object for testing. Return value true if obj can be converted to JSON data; otherwise, false.

Discussion Availability Available in iOS 5.0 and later.

0


source







All Articles