在解析为NSDictionary后,我的Swift代码中收到了以下JSON。在我的函数中,我试图在"结果"中提取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一样使用它,但在我看来它不起作用。
答案 0 :(得分:3)
results
的值不是JSON中的字典,而是数组。你应该得到这样的东西;
let allResults: NSArray = results["results"] as NSArray