json - Swift 解析使用 1 个 url api 解码 2 个不同的 json

标签 json swift parsing decode

嗨,我是 swift 的新手,我还在学习,所以我尝试制作登录 Controller 并解析 json 数据,如果它更正它解析带有 id 和东西的 json 数据,如果登录失败则 json 将显示有点信息。我已经为所有需要的值数据创建了一个结构,但是我得到了一个错误,说它为零。

所以,如果登录成功,这是 json :

[ { "id": 891, "name": "User", "email": "qdpim@immobisp.com", "status": "1" } ]

如果登录失败,这是 json :

[ { "message": "Login Failed..", "status": "0" } ]

所以基本上它有一个相同的 url 我猜?但我不知道我有点卡在这里,我需要帮助

struct login : Codable {
    let id : Int
    let name : String
    let email : String
    let status : String
    let message : String

    init(dictionary : [String : Any]) {
        id = (dictionary ["id"] as? Int)!
        name = (dictionary ["name"] as? String)!
        email = (dictionary ["email"] as? String)!
        status = (dictionary ["status"] as? String)!
        message = (dictionary ["message"] as? String)!
    }

    enum CodingKeys : String, CodingKey {
        case id = "id"
        case name = "name"
        case email = "email"
        case status = "status"
        case message = "message"
    }
}

func Login() {

    let Email = EmailField.text!
    let Pass = PasswordField.text!


    print(api)

    guard let JsonUrl = URL(string: api) else {return}
    URLSession.shared.dataTask(with: JsonUrl) { (data, response, error) in
        guard let data = data else {return}

        do{
            let parsing = try JSONDecoder().decode([login].self, from: data)
            print(parsing)
            self.Loginnn = parsing
            let stats = self.Loginnn.map { $0.status}

            if stats.contains("1"){
                print("Login Success")
                DispatchQueue.main.async {
                    self.appDelegate.loginSeque()
                }
            }else if stats.contains("0") {
                let action = UIAlertAction(title: "Got It", style:             .default, handler: nil)
                let alert = UIAlertController(title: "Wrong Email /   Password", message: "Please Try Again ", preferredStyle: .alert)
                alert.addAction(action)
                self.present(alert, animated: true, completion: nil)

                // so basicly i wanna run this alert action by search status if its contains "0"
            }
        }
    }catch{
        print(error)
    }
}.resume()
}

所以当我尝试测试登录失败时,我不会在我的日志中的 json 中显示消息,而是显示此错误

"keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))"

我只是想在登录失败时弹出一些消息或提醒,因为密码或电子邮件错误......所以也许有人可以帮助我如何以最好的方式做到这一点?

最佳答案

您可以如下声明成功和失败响应类型,

struct LoginSuccess: Decodable {
    var id: Int
    var name: String
    var email: String
    var status: String
}

struct LoginFailure: Decodable {
    var status: String
    var message: String
}

然后用作,

guard let JsonUrl = URL(string: api) else { return }
URLSession.shared.dataTask(with: JsonUrl) { (data, response, error) in
    guard let data = data else { return }

        if let success = try? JSONDecoder().decode([LoginSuccess].self, from: data).first {
            GlobalVariable.UserId = String(success.id)
            DispatchQueue.main.async {                    
                 self.appDelegate.loginSeque()
            }
        } else if let failure = try? JSONDecoder().decode([LoginFailure].self, from: data).first {
            let action = UIAlertAction(title: "Got It", style:             .default, handler: nil)
            let alert = UIAlertController(title: "Wrong Email /   Password", message: failure.message, preferredStyle: .alert)
            alert.addAction(action)
            self.present(alert, animated: true, completion: nil)
        }
}.resume()

关于json - Swift 解析使用 1 个 url api 解码 2 个不同的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56660272/

相关文章:

javascript - 将 xml 请求转换为具有重复节点名称的 json 请求

java - 如何在android动态键值对中动态获取JSON格式的输入数据

swift - 使用什么通信,updateApplicationContext 或 sendMessage 用于持续数据同步

ios - 如何获得可无延迟拖动的 MKAnnotationView?

ios - UICollectionViewLayout 小型和大型单元自动布局

java - 如何解析文本文件/需要第一个字符才能在 switch 语句中使用

javascript - 映射数组到对象

java - 如何使用 GSON 序列化 UTF-8 中的日文字符?

linux - 解析大括号中的 block

.net - 使用Roslyn进行新的语言实现