2015-05-21 31 views
10

的价值。当从web服务的解码JSON响应我得到一个错误说:无法投型“__NSArrayM”(0x34df0900)为“NSDictionary的” SWIFT

Could not cast value of type '__NSArrayM' (0x34df0900) to 'NSDictionary' 

我尝试了在StackOverflow上发现过这么多的解决方案,但没有任何工作。

我的代码:从Web Service

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": {} 
    } 
] 

谢谢您的帮助

回答

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

我希望这会帮助你!

干杯!

+0

我不在我面前,直到今晚,我会告诉你,今晚!感谢您的留言 ! – f1rstsurf

+0

现在我有:“Binary operator'!='不能应用于'NSArray'类型的操作数?' “和”nil“for”if jsonData [“message”] as?NSArray!= nil {“ – f1rstsurf

+0

如何使用类似'NSArray.count> 0'的东西来检查它是否为空或空? –

4

使用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 
} 
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) 
相关问题