Juan Rangel
Juan Rangel

Reputation: 1793

Parsing JSON Errors with Swift

What's the best way to parse this JSON using swift?

{
    "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."
        ]
    }
}

I am using these decodable structs

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]?
}

but it does not feel flexible enough.

My app is talking to a web app and I keep running into this problem over and over again and can't seem to get it right. These validation errors are dynamic and at times there may only be one error, so I'm trying to count for different errors being thrown. Any help would be appreciated.

Upvotes: 0

Views: 63

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100523

I guess you need

struct AuthError: Codable {
  let message: String
  let errors: [String:[String]]
}

since a key may not exists then using Codable with static keys will fail

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

also using SwiftyJSON is another good option here

Upvotes: 1

Related Questions