我有一个异步调用的 JSON 数据,我的问题是,如何从 item:1 调用标题
{
"rss": {
"channel": {
"atom:link": "",
"title": "The Local",
"link": "http://www.thelocal.se/",
"description": "Sweden's news in English",
"language": "en-us",
"managingEditor": "TheLocal",
"webMaster": "TheLocal",
"generator": "TheLocal RSS Feed Generator",
"item:0": {
"title": "Knausgård savages the 'Cyclops' Swedes",
"description": "Norwegian literary star Karl Ove Knausgård has launched an extraordinary attack on the Swedes, damning them as a race of narrow-minded “cyclops” who cannot tolerate ambiguity, have no understanding of literature, and are “full of hate and fear”.",
"link": "http://www.thelocal.se/20150520/knausgrd-savages-the-cyclops-swedes",
"pubDate": "2015-05-20 15:25:25",
"guid": "http://www.thelocal.se/20150520/knausgrd-savages-the-cyclops-swedes"
},
"item:1": {
"title": "Migration Board worker took bribes for passports",
"description": "A court in Malmö has jailed a former Migration Board worker and his accomplice for taking bribes in exchange for residence permits and passports for asylum seekers desperate to stay in Sweden.",
"link": "http://www.thelocal.se/20150520/two-found-guilty-in-migration-board-bribery-case",
"pubDate": "2015-05-20 12:32:46",
"guid": "http://www.thelocal.se/20150520/two-found-guilty-in-migration-board-bribery-case"
},
"item:2": {
"title": "Two million Swedes design 'house of clicks'",
"description": "A team of award-winning architects have joined forces with two million Swedes to design the country’s most sought-after home.",
"link": "http://www.thelocal.se/20150520/two-million-swedes-design-dream-house-of-clicks",
"pubDate": "2015-05-20 12:01:35",
"guid": "http://www.thelocal.se/20150520/two-million-swedes-design-dream-house-of-clicks"
},
我现在无法编译的代码是:
if var jsonArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? Array<NSDictionary> {
println("jsonArray: \(jsonArray)")
dispatch_async(dispatch_get_main_queue()) {
for var i:Int = 0; i < jsonArray.count; i++ {
var title:String = jsonArray["rss"]["item:\(i)"].valueForKey("title") as String
所以我的想法是,我将如上所示调用每个缩进,但现在它说 AnyObject?没有名为 valueForKey 的成员。
我认为这是我从数组字典中调用信息的格式。
有人可以帮助我吗,因为试图向谷歌描述这个问题让我很难解释,因为它很难解释。
最佳答案
首先,您的 JSON 不是 Array
,因此在序列化结束时将其转换为 NSDictionary
(其中具有 valueForKeyPath
方法)方法。
然后只需使用
if let item1title = json?.valueForKeyPath("rss.channel.item:1.title") {
//here you are ready tu use it
}
关于json - 在 Swift 中使用大缩进调用 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30354262/