JSON Codable with Custom Keys

Flexible Codable implementation with custom JSON keys and default values for missing fields.

← Back
Language: swift | Tags: codable json parsing api
struct User: Codable {
    let id: Int
    let username: String
    let email: String
    let createdAt: Date
    var isVerified: Bool = false

    enum CodingKeys: String, CodingKey {
        case id
        case username = "user_name"
        case email = "email_address"
        case createdAt = "created_at"
        case isVerified = "is_verified"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(Int.self, forKey: .id)
        username = try container.decode(String.self, forKey: .username)
        email = try container.decode(String.self, forKey: .email)
        createdAt = try container.decode(Date.self, forKey: .createdAt)
        isVerified = try container.decodeIfPresent(Bool.self, forKey: .isVerified) ?? false
    }
}