如何在Swift 4中使用Alamofire 4.7解析JSON [英] How to parse JSON using Alamofire 4.7 in Swift 4

查看:240
本文介绍了如何在Swift 4中使用Alamofire 4.7解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

问题:可以吗? t弄清楚如何从JSON响应中检索数据,主要是 api_key

Problem: Can't figure out how to retrieve data from JSON response, mainly 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")
        }

当我打印(响应)时,我得到以下信息:

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 = "admin@demo.com";
        status = 1;
    }; 
}

我需要得到的是


api_key = 9a13f31770b80767a57d753961acbd3a18eb1370;

"api_key" = 9a13f31770b80767a57d753961acbd3a18eb1370;

它可以是数组形式,dict或仅包含以下字符串:

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


9a13f31770b807 ...

9a13f31770b807...

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

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

编辑

print(response.result。值):

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


推荐答案

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

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
}

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

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)

这篇关于如何在Swift 4中使用Alamofire 4.7解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆