用大缩进在Swift中调用json

时间:2015-05-20 15:36:16

标签: json swift ios8

我在async中调用了一个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的成员。

我在想它是从格式字典中调用信息的格式。

有人可以帮助我,因为试图描述这个问题谷歌让我难以理解,因为很难解释。

1 个答案:

答案 0 :(得分:1)

首先,您的JSON不是Array,因此在序列化方法结束时将其强制转换为NSDictionary(具有valueForKeyPath方法)。 然后使用

if let item1title = json?.valueForKeyPath("rss.channel.item:1.title") {
    //here you are ready tu use it
}