0

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>";
};
}])

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
Stefan Badertscher
  • 331
  • 1
  • 6
  • 20
  • try to use NSJSONSerialization.JSONObjectWithData(responseObject!, options: NSJSONReadingOptions.MutableContainers) – Lu_ Aug 03 '16 at 12:07
  • 1
    **response!["result"] as? [AnyObject]** - this is an issue. The object is not a [AnyObject], it's a Dictionary. – Michal Aug 03 '16 at 12:08

2 Answers2

3

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

let result = response!["result"]  as? [String:AnyObject]
Nirav D
  • 71,513
  • 12
  • 161
  • 183
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
}
Abedalkareem Omreyh
  • 2,180
  • 1
  • 16
  • 20