Search code examples
swiftnsjsonserializationdecodable

Why Swift JSONDecodable fails?


I try to decode the errors from HTTP request using JSONDecodable but it fails.

I have created a custom class and extended with Decodable.

class CustomError: Decodable {

    // Properties
    var errors: [String: [String:String]]?
    var message: String?
}

And using the following line to decode which returns nil:

let jsonError = try? JSONDecoder().decode(CustomError.self, from: data!)

But I get the following resulting using JSONSerialization:

let jsonError = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

Result:

Optional({
    errors =     {
        email =         (
            "The email has already been taken."
        );
    };
    message = "The given data was invalid.";
})

Any reason why the Decodable doesn't work?


Solution

  • You need to do this because you have the array of values(email) in errors:

    var errors: [String: [String]]?