无法将'__NSArrayM'(0x34df0900)类型的值转换为'NSDictionary'SWIFT

f1r*_*urf 11 json web-services nsdictionary ios swift

从webservice解码JSON响应时,我收到一条错误消息:

Could not cast value of type '__NSArrayM' (0x34df0900) to 'NSDictionary'
Run Code Online (Sandbox Code Playgroud)

我尝试了在StackOverflow中找到的很多解决方案,但没有任何效果.

我的代码:

let jsonData:NSDictionary = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary)!

let success:NSInteger = jsonData.valueForKey("success") as! NSInteger
Run Code Online (Sandbox Code Playgroud)

来自Web服务的响应:

[
    {
        "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": {}
    }
]
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助

Ran*_*man 12

尝试替换以下行:

let jsonData:NSDictionary = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary)!
Run Code Online (Sandbox Code Playgroud)

有以下几点:

let jsonData:NSArray = (NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSArray)!
Run Code Online (Sandbox Code Playgroud)

我希望这能帮到您!

干杯!


all*_*bto 5

使用SwiftyJSON:https://github.com/SwiftyJSON/SwiftyJSON

let json = JSON(data: urlData!)
Run Code Online (Sandbox Code Playgroud)

如果成功在阵列中

if let success = json[0]["success"].int {
     //Now you got your value
}
Run Code Online (Sandbox Code Playgroud)

或者如果成功不在数组中

if let success = json["success"].int {
     //Now you got your value
}
Run Code Online (Sandbox Code Playgroud)

您还可以检查成功值

if let success = json["success"].int where success == 1 {
     // Now you can do stuff
}
Run Code Online (Sandbox Code Playgroud)