如何在Swift中的括号中访问嵌套的JSON?

时间:2016-08-03 12:04:46

标签: arrays swift parsing

我有一个JSON响应,它在括号中,我很难访问内部字段,例如带Swift的display_name。我怎么能这样做?

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

我用来访问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)

             }
    }

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

控制台输出:

result object
nil

2 个答案:

答案 0 :(得分:2)

作为回应,结果为dictionary而不是array,请尝试这样做

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

答案 1 :(得分:0)

1 - 从响应中获取结果对象
2 - 从结果对象中获取用户对象
3 - 从用户对象获取用户信息为String。

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

if let user = result!["user"]  as? [String: AnyObject] {
        let displayName = user["display_name"] as? String
        let email = user["email"] as? String
}