如何在Swift中的括号中访问嵌套的JSON? [英] How to access nested JSON in brackets in Swift?

查看:67
本文介绍了如何在Swift中的括号中访问嵌套的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个放在方括号中的JSON响应,我很难访问内部字段,例如使用Swift的display_name.我该怎么办?

I have a JSON response which is in brackets and I struggle to access the inner fields e.g. display_name with Swift. How can I do that?

Optional(["result": {
user =     {
    "display_name" = "Max Test";
    email = "test.max@gmail.com";
    "fb_id" = 10209982554704497;
    roles =         (
        stu
    );
    schools = "<null>";
};
}])

我用来访问JSON的代码:

The code I used to access the JSON:

 self.restApi.getProfileDetails() {responseObject, error in

        //parse down the first layer of array
        let response = responseObject as? [String:AnyObject]
        print("response object when MyDetailsController opened")
        print(response)

        let result = response!["result"]  as? [AnyObject]
        print("result object")
        print(result)

        //parse down the second layer of JSON object
        if let result = response!["result"]  as? [AnyObject] {

            print("result object when MyDetailsController opened")
            // work with the content of "result", for example:
            if let user = result[0] as? [String:AnyObject]{
                print(user)

                let displayName = user["display_name"]
                print("displayName")
                print(displayName)

             }
    }

似乎我总是以错误的方式处理结果,因为它始终为零:

It seems that I address the result in the wrong way as it is always nil:

控制台输出:

result object
nil

推荐答案

响应结果是dictionary而不是array,请尝试像这样

In response result is dictionary not array, try to get like this

let result = response!["result"]  as? [String:AnyObject]

这篇关于如何在Swift中的括号中访问嵌套的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆