json - 解析 JSON 中的嵌套元素

标签 json swift

我似乎无法解析以下 json:

["data": {
    companies =     (
    );
    "login_status" = success;
    "rs_customer" =     {
        id = "<null>";
        name = "<null>";
        status = "<null>";
    };
    user =     {
        email = "email@email.com";
        id = 0;
        lastlogin = "06/14/16 12:44 am";
        name = "Jayson Tamayo";
        password = mypassword;
        phone = "112345";
    };
}, "status": success]

我通过以下方式检索 JSON:

HTTPGetJSON("http://myurl.com") {
                (data: Dictionary<String, AnyObject>, error: String?) -> Void in
                if error != nil {
                    print(error)
                } else {
                    print(data)
                    let status = data["status"] as? String
                    print(status)

                }
            }

当我打印“状态”时,它起作用了。但是当我尝试使用 data["name"] 时,我得到了零。我也尝试过 data["data"]["name"] 但我也得到 nil。

最佳答案

你的主要对象是一本字典。

在“data”键中,有几个值:“companies”是一个数组,“rs_customer”是一个字典,状态是字符串,“user”是一个字典。

因此,要获得用户,您只需转换为正确的类型,就像这样,如果 data 是我们在问题中看到的对象:

if let content = data["data"] as? [String:AnyObject] {
    if let user = content["user"] as? [String:AnyObject] {
        if let name = user["name"] as? String {
            print(name)
        }   
    }
}

您还可以链接展开以获得更简单的代码:

if let content = data["data"] as? [String:AnyObject],
        user = content["user"] as? [String:AnyObject],
        name = user["name"] as? String {
    print(name)
}

关于json - 解析 JSON 中的嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37803981/

相关文章:

php - 以 JSON 格式返回 MySQL 数据

javascript - 合并 JSON 数组中的重复值(最好使用下划线或 lodash)

ios - 如何在 Swift 中使 iPhone 状态栏透明?

swift - Swift方法 header 的数据类型中的感叹号是什么意思

swift - 禁止 swift 中间接枚举的一些特定情况

ios - 分页 UIScrollView "Prototype Pages"

javascript - 如何将 JSON 数据存储和检索到本地存储?

iphone - 将 URL 解码为 JSON

javascript - jQuery 是否支持从 X-JSON HTTP header 读取 JSON?

ios-防止滚动时重新加载 UITableView 中的单元格