Не удалось передать значение типа "__NSArrayM" (0x34df0900) в "NSDictionary" SWIFT
При декодировании ответа JSON от webservice я получаю сообщение об ошибке:
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": {}
}
]
Спасибо за помощь
Ответы
Ответ 1
Попробуйте заменить следующую строку:
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)!
Я надеюсь, что это поможет вам!
Ура!
Ответ 2
Использовать 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, не удалось передать значение типа '__NSArrayM' (0x507b58) в 'NSDictionary' (0x507d74)
Фактическое содержимое объекта находилось внутри NSDictionary в индексе 0 этого массива. Попробуйте с этим кодом (включая некоторые строки журнала, чтобы проиллюстрировать)
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)