在SwiftyJSON中正确循环和检索值

时间:2015-07-11 22:33:01

标签: ios json swift swifty-json

我正在尝试找到一种在SwiftyJSON中循环和检索值的正确方法。 请参阅以下代码中的评论。

audioReq.executeWithResultBlock({
            response in
            let json = JSON(response.json)
            for (key, subJson) in json {
                if let title = subJson[key].string {   //<-- Loop does not work! 
                    println(title)                    //     It prints nothing!
                }
            }

            if let title = json[0]["first_name"].string {
                println(title)                                  //<-- Works
            }
            if let title = json[0]["last_name"].string {
                println(title)                                 //<-- Works
            }
            if let title = json[0][1].string {
                println(title)                        //<-- Does not work!
            }                                         //  Prints nothing!

            if let title = json[0]["id"].string {
                println(title)                        //<-- Does not work!
            }                                         //  Prints nothing!
            println(response.json)
                                   },
            errorBlock: {(error:NSError!) -> Void in
                println(error.localizedDescription)
        })

response.json的内容:

(
        {
        "first_name" = "Dachnik";
        id = 12345678;               // should be  "id" = 12345678
        "last_name" = "Neudachnik";
    }
)

1 个答案:

答案 0 :(得分:1)

您正在使用数组而不是字典。应该做些什么

for (key, subJson) in json[0] {
    if let title = subJson[key].string {   //<-- Loop does not work! 
        println(title)                    //     It prints nothing!
    }
}

如果你有多个用户,那么你应该做一些事情(这里没有MAC)

for dict in json {
    // go through dictionary elements here: first_name, last_name, id
    // you can use same for loop as above
}