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

编程入门 行业动态 更新时间:2024-10-26 01:34:09
本文介绍了如何在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"; 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"; 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

本文发布于:2023-11-26 01:56:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632184.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Swift   Alamofire   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!