Search code examples
swiftenumscodabledecodable

Codable Decodable JSON from String to Enum


I'm trying to decode a JSON using codable. I'm wondering if there's a way to customize codable to return HelloModel's typeCustomer as type TypeOfCustomerEnum instead of String?

Example:

{
"name": "Hello",
"lastName": "World",
"typeOfCustomer": "Student"
}

enum TypeOfCustomerEnum: String {
   let Student = "Student"
   let Paying = "Paying"
   let NonPaying = "Nonpaying"
}

struct HelloModel: Codable {
   let name: String
   let lastName: String
   let typeOfCustomer: TypeOfCustomerEnum // JSON for TypeOfCustomer is a String but TypeOfCustomer wanted
}

Solution

  • The type TypeOfCustomerEnum must also conform to Codable and the cases (must be cases) should be lowercased and the literal strings must match the JSON values

    enum TypeOfCustomerEnum: String, Codable {
       case student = "Student"
       case paying = "Paying"
       case nonPaying = "NonPaying"
    }
    
    struct HelloModel: Codable {
       let name: String
       let lastName: String
       let typeOfCustomer: TypeOfCustomerEnum 
    }