如何在alamofire中使用JSON元素

编程入门 行业动态 更新时间:2024-10-26 03:39:38
本文介绍了如何在alamofire中使用JSON元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用两个文本字段以以下方式使用Alamofire将登录信息传递给PHP Web服务.

I am using two textfields to pass login information to the PHP web service using Alamofire in the following way.

@IBAction func LoginButton(_ sender: Any) { //getting the username and password let parameters: Parameters=[ "Name":TextFieldUserName.text!, "Pass":TextFieldPassword.text! ] Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON { response in //printing response print(response)

登录时会收到以下Json数据.

The following Json data is received on login.

[{"code":0,"message":"Check Username and Password....","userid":""}]

我想使用"code"值(0表示false,1表示true)或"message"值作为String放入if-else语句中,以进行进一步的操作.如果Alamofire并非解决此问题的最佳方法,请有人可以提出另一种方法.预先感谢您的帮助.

I want to use either "code" value (0 for false and 1 for true) or "message" value as String to put into an if - else statement for further steps. If Alamofire is not the best way to go about this, can someone please show another way. Thanks in advance for the help.

推荐答案

是否需要反序列化服务器的响应?

Do you need to deserialize the response from the server?

最简单的选择是将响应值解析为NSDictionary

The easiest option is parsing response value as NSDictionary

if let JSON = response.result.value as? NSDictionary { let code = JSON.value(forKey: "code") as? Int let message = JSON.value(forKey: "message") as? String }

您还可以使用Codable协议和JSONDecoder将此响应解码为您的结构.

You can also use the Codable protocol and the JSONDecoder to decode this response into your structure.

例如,声明struct:

For example, declare struct:

struct LoginResponse: Codable { var code: Int var message: String }

并使用JSONDecoder解码响应

and decode response using JSONDecoder

let jsonDecoder = JSONDecoder() let loginResponse = try? jsonDecoder.decode(LoginResponse.self, from: response.data)

更多推荐

如何在alamofire中使用JSON元素

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

发布评论

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

>www.elefans.com

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