0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! That looks like what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.