Swift:从 JSON 数组的内部项创建字典

Swift: Create Dictionary from Inner Items of JSON Array

在 Swift 中,我有一个 POST 对 URL 的请求,其中 returns JSON 类似于:

{"users":[{
"user":{"userID":"1","userName":"John"}},
{"user":{"userID":"2","userName":"Mary"}},
{"user":{"userID":"3","userName":"Steve"}},
]}

这是 Swift 代码:

var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
println(result?.count)
println(result)

...输出这个:

Optional(1)
Optional({
    users = ({
        user = {
                userID = 1;
                userName = John;
            };
        },
            {
        user = {
                userID = 2;
                userName = Mary;
            };
        },
            {
        user = {
            userID = 3;
            userName = "Steve";
        };
    });
})

我正在尝试遍历 "user" 元素,但我尝试的任何操作都不起作用。我有一本 "user" 级别 JSON 的字典,但不知道如何继续获取此 "users" 的子级。有谁知道我该怎么做?如果我可以通过它们查看 println() 用户名​​,那将是一个很好的开始。

试试这个。

var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary

if let users = result?.objectForKey("users") as? [[String:AnyObject]]
{
    for user in users
    {
        if let userValues = user["user"] as? [String:AnyObject]
        {
            println(userValues["userID"]!)
            println(userValues["userName"]!)
        }

    }
}