Decode JSON object to plain String in Swift

You can make that happen by implementing the decoding yourself in ApiData and searching for each player id in the players array:

struct ApiResponse: Decodable {
    let data: ApiData

struct ApiData: Decodable {
    let players: [Player]
    var games: [Game]
    enum CodingKeys: String, CodingKey {
        case players
        case games
    enum GameCodingKeys: String, CodingKey {
        case name
        case playerId1
        case playerId2
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        players = try container.decode([Player].self, forKey: .players)
        var gamesContainer = try container.nestedUnkeyedContainer(forKey: .games)
        games = []
        while !gamesContainer.isAtEnd {
            let gameContainer = try gamesContainer.nestedContainer(keyedBy: GameCodingKeys.self)
            let playerId1 = try gameContainer.decode(Int.self, forKey: .playerId1)
            let playerId2 = try gameContainer.decode(Int.self, forKey: .playerId2)
                let player1 = players.first(where: { $ == playerId1 }),
                let player2 = players.first(where: { $ == playerId2 })
            else { continue }
            let game = Game(
                name: try gameContainer.decode(String.self, forKey: .name),
                player1: player1,
                player2: player2

struct Player: Decodable {
    var id: Int
    var name: String?

struct Game: Decodable {
    var name: String
    var player1: Player
    var player2: Player

It’s a little ugly, but in the end you can use it like this:

let decoder = JSONDecoder()
do {
    let response = try decoder.decode(ApiResponse.self, from: .utf8)!)
    let games =
} catch {

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top