Reputation: 647
When decoding JSON response from webservice I get an error saying:
Could not cast value of type '__NSArrayM' (0x34df0900) to 'NSDictionary'
I tried out so many solutions found in StackOverflow too, but nothing works.
My Code :
let jsonData:NSDictionary = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary)!
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
Response from the Web Service:
[
{
"id": "1",
"title": "bmw",
"price": "500.00",
"description": "330",
"addedDate": "2015-05-18 00:00:00",
"user_id": "1",
"user_name": "CANOVAS",
"user_zipCode": "32767",
"category_id": "1",
"category_label": "VEHICULES",
"subcategory_id": "2",
"subcategory_label": "Motos",
"bdd": {}
}
]
Thank you for your help
Upvotes: 13
Views: 21601
Reputation: 181
This will happen if you miss a "level" reading the logs. I was encountering this error, tried casting to an NSArray instead of NSMutableDictionary as here Swift JSON error, Could not cast value of type '__NSArrayM' (0x507b58) to 'NSDictionary' (0x507d74)
The actual contents of the object were inside an NSDictionary at index 0 of that array. Try with this code (including some log lines to illustrate)
let dataDict = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error)
println(dataDict)
let contents = dataDict!.objectForKey("rows") as! NSMutableArray
println(contents)
println( "contents is = \(_stdlib_getDemangledTypeName(contents))")
let innerContents = contents[0]
println(innerContents)
println( "inner contents is = \(_stdlib_getDemangledTypeName(innerContents))")
let yourKey = innerContents.objectForKey("yourKey") as? String
println(yourKey)
Upvotes: 3
Reputation: 169
Use SwiftyJSON : https://github.com/SwiftyJSON/SwiftyJSON
let json = JSON(data: urlData!)
And if success is in the array
if let success = json[0]["success"].int {
//Now you got your value
}
Or if success is not in the array
if let success = json["success"].int {
//Now you got your value
}
You can also check success value
if let success = json["success"].int where success == 1 {
// Now you can do stuff
}
Upvotes: 5
Reputation: 8124
Try replacing following line:
let jsonData:NSDictionary = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary)!
With following:
let jsonData:NSArray = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSArray)!
I hope this will help you!
Cheers!
Upvotes: 12