使用Swift解析JSON错误

使用Swift解析JSON错误,swift,Swift,使用swift解析此JSON的最佳方法是什么 { "message": "The given data was invalid.", "errors": { "first_name": [ "The first name field is required." ], "last_name": [ "The last name field is required." ],

使用swift解析此JSON的最佳方法是什么

{
    "message": "The given data was invalid.",
    "errors": {
        "first_name": [
            "The first name field is required."
        ],
        "last_name": [
            "The last name field is required."
        ],
        "email": [
            "The email field is required."
        ],
        "password": [
            "The password field is required."
        ],
        "dob": [
            "The dob field is required."
        ]
    }
}
我正在使用这些可解码结构

struct AuthError: Codable {
    let error: String?
    let errors: APIError
    let message: String
}
struct APIError: Codable {
    let email: [String]?
    let dob: [String]?
    let first_name: [String]?
    let last_name: [String]?
    let password: [String]?
}
但它感觉不够灵活

我的应用程序正在与一个web应用程序进行通信,我不断地遇到这个问题,但似乎无法正确处理。这些验证错误是动态的,有时可能只有一个错误,所以我试图计算抛出的不同错误。任何帮助都将不胜感激。

我想你需要帮助

struct AuthError: Codable {
  let message: String
  let errors: [String:[String]]
}
由于密钥可能不存在,因此将Codable与静态密钥一起使用将失败

let res = try! JSONDecoder().decode(AuthError.self, from: data)
if let fname = res.errors["first_name"]?.first {
  print(fname)
}

另外,使用迅捷JSON也是一个不错的选择

非常感谢!这看起来是我需要的。