如何在alamofire中使用JSON元素 [英] How do I use JSON element with alamofire

查看:129
本文介绍了如何在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元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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