Ad

How To Parse JSON Using Alamofire 4.7 In Swift 4

- 1 answer

I know this question was asked before, but answers were in Swift 3 and using older versions of Alamofire.

Problem: Can't figure out how to retrieve data from JSON response, mainly api_key.

Here is code for my response:

Alamofire.request(serverLink!, headers: headers).responseJSON{ response in

        if response.value != nil {
            //Some code to get api_key
            print(response)
        } else {
            print("error")
        }

When I print(response) I get the following:

        SUCCESS: {
    user =     {
        "api_key" = 9a13f31770b80767a57d753961acbd3a18eb1370;
        "created_on" = "2010-09-30T12:57:42Z";
        firstname = Paul;
        id = 4;
        "last_login_on" = "2018-03-27T10:15:10+03:00";
        lastname = Smith;
        login = admin;
        mail = "[email protected]";
        status = 1;
    }; 
}

What I need to get is

"api_key" = 9a13f31770b80767a57d753961acbd3a18eb1370;

It could be in form of array, dict or just string containing:

9a13f31770b807...

Could someone please explain to me how to get(decode) it from this request?

EDIT

print(response.result.value):

RESPONSE: Optional({ user = { "api_key" = 9a13f31770b80767a57d753961acbd3a18eb1370; "created_on" = "2010-09-30T12:57:42Z"; firstname = Paul; id = 4; "last_login_on" = "2018-03-27T11:10:25+03:00"; lastname = Smith; login = admin; mail = "[email protected]"; status = 1; }; })
Ad

Answer

As per the docs, this is how you access the serialised JSON response:

if let json = response.result.value as? [String: Any] {
    print("JSON: \(json)") // serialized json response
}

To access api_key you just need to unwrap the success and user dictionaries first and then you can access the api_key property in the user dictionary.

guard let user = json["user"] as? [String: Any],
      let apiKey = user["api_key"] as? String else {

      print("Failed to parse JSON")
      return
}

print(apiKey)
Ad
source: stackoverflow.com
Ad