Murat Kaya
Murat Kaya

Reputation: 1321

Could not cast value of type '__NSArrayM' to 'NSDictionary'

I have a json.I am trying to parse that with that code.But its says

Could not cast value of type '__NSArrayM' to 'NSDictionary'

do {
    let dataDictionary: NSDictionary = try NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary // <------ Error

    if let customerArray = dataDictionary.valueForKey("cart") as? NSArray {
        for js in customerArray {
            let nameArray = js.valueForKey("name")
            let idArray = js.valueForKey("id")
        }
    }
}

Thank you for your helps

Upvotes: 0

Views: 4109

Answers (2)

Gavin
Gavin

Reputation: 8200

What it's telling you is that the JSON object that you're parsing is not a dictionary, it's an array. So if you change it so that you treat its value as an array instead of a dictionary, you'll be able to iterate over that.

You need to reevaluate your JSON to ensure that it's structured the way you think it is. It would also be useful if you posted the JSON that you're trying to parse so that we can see it's structure as well.

Upvotes: 1

L&#233;o Natan
L&#233;o Natan

Reputation: 57060

The root object in your data is an array, not a object (dictionary).

You need to dynamically decide how to handle your JSON depending on the deserialized object.

Upvotes: 1

Related Questions