1

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 = "[email protected]";
    "fb_id" = 10209982554704497;
    roles =         (
        stu
    );
    schools = "<null>";
};
}])

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:

The console output:

result object
nil
2
  • try to use NSJSONSerialization.JSONObjectWithData(responseObject!, options: NSJSONReadingOptions.MutableContainers) Commented Aug 3, 2016 at 12:07
  • 1
    response!["result"] as? [AnyObject] - this is an issue. The object is not a [AnyObject], it's a Dictionary. Commented Aug 3, 2016 at 12:08

2 Answers 2

3

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

let result = response!["result"]  as? [String:AnyObject]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this helped. Thank you
1

1-Get the result object from response
2-Get the user object from result object
3-Get the user info as String from user object .

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.