Home > front end >  How to decode a property with type of JSON dictionary
How to decode a property with type of JSON dictionary

Time:01-19

{
    "data": {
        "player_id": 184798,
        "team_id": 83,
        "country_id": 44,
        "position_id": 4,
        "common_name": "L. Messi",
        "display_name": "Lionel Messi",
        "fullname": "Lionel Andrés Messi Cuccittini",
        "firstname": "Lionel Andrés",
        "lastname": "Messi Cuccittini",
        "nationality": "Argentina",
        "birthdate": "24/06/1987",
        "birthcountry": "Argentina",
        "birthplace": "Rosario"
     }
}

The response is in this form, let me know how to declare my struct with appropriate declaration.

CodePudding user response:

This should work (feel free to change the names of the structs):

struct PlayerData: Codable {
    let data: PlayerInfo?
}

struct PlayerInfo: Codable {
    let playerId, teamId, countryId, positionId: Int?
    let commonName, displayName, fullname, firstname: String?
    let lastname, nationality, birthdate, birthcountry: String?
    let birthplace: String?

    enum CodingKeys: String, CodingKey {
        case playerId = "player_id"
        case teamId = "team_id"
        case countryId = "country_id"
        case positionId = "position_id"
        case commonName = "common_name"
        case displayName = "display_name"
        case fullname, firstname, lastname, nationality, birthdate, birthcountry, birthplace
    }
}
  • Related