如何在 Swift 4 中使用 Alamofire 4.7 解析 JSON

Tar*_*huk -4 json decode ios swift alamofire

我知道之前有人问过这个问题,但答案是在 Swift 3 中并使用旧版本的 Alamofire。

问题:无法弄清楚如何从 JSON 响应中检索数据,主要是api_key

这是我的回复代码:

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

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

当我print(response)得到以下信息时:

        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 = "admin@demo.com";
        status = 1;
    }; 
}
Run Code Online (Sandbox Code Playgroud)

我需要得到的是

“api_key”= 9a13f31770b80767a57d753961acbd3a18eb1370;

它可以是数组、字典或仅包含以下内容的字符串形式:

9a13f31770b807...

有人可以向我解释如何从这个请求中获取(解码)它吗?

编辑

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 = "admin@demo.com"; status = 1; }; })
Run Code Online (Sandbox Code Playgroud)

Scr*_*ble 7

根据docs,这是访问序列化 JSON 响应的方式:

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

要访问api_key您只需要先打开成功和用户字典,然后您就可以访问用户字典中的 api_key 属性。

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

      print("Failed to parse JSON")
      return
}

print(apiKey)
Run Code Online (Sandbox Code Playgroud)