在被解析为 NSDictionary 之后,我的 Swift 代码中收到了以下 JSON。在我的函数中,我试图将“结果” block 中的 JSON 对象提取为 NSDIctionary[],但这会引发运行时错误。我不明白为什么,因为这几天前还在工作。
{
"results": [
{
"id": "3",
"name": "The National",
"slug": "thenational",
"facebook_url": "https://www.facebook.com/thenationalofficial/",
"twitter_url": "https://twitter.com/The_National",
"profile_image": "http://example.staging.com/media/profile_image/thumbnail_263x263/1352756032.jpg",
"_type": "artist",
"resource_uris": {
}
},
{
"id": "5",
"name": "Mayer Hawthorne",
"slug": "mayerhawthorne",
"facebook_url": "https://www.facebook.com/MayerHawthorne",
"twitter_url": "https://twitter.com/MayerHawthorne",
"profile_image": "http://example.example.com/media/profile_image/thumbnail_263x263/1352755133.png",
"_type": "artist",
"resource_uris": {
}
},
{
"id": "20",
"name": "I Play Maracas",
"slug": "iplaymaracas",
"facebook_url": "",
"twitter_url": "",
"profile_image": "http://staging.wedemand.com/images/en/img-list-home.gif",
"_type": "artist",
"resource_uris": {
"_demanded_by": null,
"demand_url": "http://ec2-54-86-17-163.compute-1.amazonaws.com/artists/20/?demand=1&access_token={}",
"dismiss_url": "http://ec2-54-86-17-163.compute-1.amazonaws.com/artists/20/?demand=0&access_token={}"
}
},
{
"id": "35",
"name": "Black SuperHeros",
"slug": "blacksuperheros",
"facebook_url": "",
"twitter_url": "",
"profile_image": "http://staging.example.com/images/en/img-list-home.gif",
"_type": "artist",
"resource_uris": {
}
},
{
"id": "49",
"name": "Ayman Elgadi",
"slug": "aymanelgadi",
"facebook_url": "",
"twitter_url": "",
"profile_image": "http://staging.example.com/images/en/img-list-home.gif",
"_type": "artist",
"resource_uris": {
}
},
{
"id": "8874",
"name": "Lauri",
"slug": "lauri",
"facebook_url": "http://www.facebook.com/hughlaurieblues",
"twitter_url": "http://twitter.com/hughlaurieblues",
"profile_image": "http://staging.example.com/media/profile_image/thumbnail_263x263/lauri_profilepic.jpg",
"_type": "artist",
"resource_uris": {
}
}
]
}
我的 IOS-Swift 代码在被 AFNetworking lib 解析后接收到 NSDictionary 对象,并将其传递给将结果数组转换为 NSDictionary[] 的函数,现在抛出运行时错误,而早些时候这是有效的。
(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in println("JSON: " + responseObject.description)
var jsonResult: NSDictionary = responseObject as NSDictionary
这个 jsonResult 被传递给下面的函数,它试图转换为 NSDictionary[]
let allResults: NSDictionary[] = results["results"] as NSDictionary[]
更新: 我打印了结果对象的类,因为它作为 __NSCFDictionary 返回。
在这里What is an NSCFDictionary?是关于此的讨论,并说要像 NSDictionary 一样使用它,但在我的情况下它不起作用。
最佳答案
results
的值不是 JSON 中的字典,而是一个数组。你应该用这样的东西得到它;
let allResults: NSArray = results["results"] as NSArray
关于ios - 来自 JSON 的数据转换结果为 NSDictionary[] 抛出 EXC_BAD_INSTRUCTION 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24392949/