2015-05-21 66 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) 
相關問題