从webservice解码JSON响应时,我收到错误消息:
Could not cast value of type '__NSArrayM' (0x34df0900) to 'NSDictionary'
我在StackOverflow中尝试了很多解决方案,但没有任何效果。
我的代码:
let jsonData:NSDictionary = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary)!
let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
来自网络服务的回复:
[
{
"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": {}
}
]
感谢您的帮助
答案 0 :(得分:12)
尝试更换以下行:
let jsonData:NSDictionary = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary)!
以下:
let jsonData:NSArray = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSArray)!
我希望这会对你有所帮助!
干杯!
答案 1 :(得分:5)
使用SwiftyJSON:https://github.com/SwiftyJSON/SwiftyJSON
let json = JSON(data: urlData!)
如果成功在数组中
if let success = json[0]["success"].int {
//Now you got your value
}
或者如果成功不在数组中
if let success = json["success"].int {
//Now you got your value
}
您还可以检查成功值
if let success = json["success"].int where success == 1 {
// Now you can do stuff
}
答案 2 :(得分:3)
如果您错过了读取日志的“级别”,则会发生这种情况。我遇到了这个错误,尝试在这里转换为NSArray而不是NSMutableDictionary Swift JSON error, Could not cast value of type '__NSArrayM' (0x507b58) to 'NSDictionary' (0x507d74)
对象的实际内容位于该数组的索引0处的NSDictionary内。尝试使用此代码(包括一些日志行来说明)
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)