简体   繁体   中英

Decode JSON object with array and not a dictionary

I'm using an API that returns a JSON object in the following format:

{
    "cards": [
        {
            "name": "Charizard"
        },
        ...
    ]
}

When I try to decode this, it says it it's not valid JSON... it says it expected an array but got a dictionary. I have a feeling it's because I not actually selecting the cards array from the object? But I can't figure out how to modify my snippet to achieve it...

import SwiftUI

struct Card: Codable {
    var name: String
}

class Api {
    func getCards(completion: @escaping ([Card]) -> ()) {
        guard let url = URL(string: "https://api.pokemontcg.io/v1/cards") else { return }
        
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            let cards = try! JSONDecoder().decode([Card].self, from: data!)
    
            print(cards)
            
            //DispatchQueue.main.async {
            //    completion(cards)
            //}
        }
        .resume()
    }
}

You forgot to decode the top level JSON object.

You can either create another struct like this:

struct Response: Codable {
    var cards: [Card]
}

and use the following code to decode your JSON:

do {
    let response = try JSONDecoder().decode(Response.self, from: data!)
} catch {
    print(error)
}

or you can use [String: [Card]] as decoding type:

do {
    let response = try JSONDecoder().decode([String: [Card]].self, from: data!)
} catch {
    print(error)
}

Either way, never use try! . It is always better to do-catch and print the error that you might get.

So what you're trying to decode is not actually an array of Card , but an object which has a property cards which is an array of Card . So try creating a struct for the container and decoding that.

struct CardResponse: Codable {
    let cards: [Card]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM