首页 文章

Swift Decoding嵌套JSON

提问于
浏览
0

我在解析来自NBP api“http://api.nbp.pl/api/exchangerates/tables/a/?format=json”的数据时遇到问题 . 我创建了struct CurrencyDataStore和Currency

struct CurrencyDataStore: Codable {
var table: String
var no : String
var rates: [Currency]

enum CodingKeys: String, CodingKey {
    case table
    case no
    case rates
}

init(from decoder: Decoder) throws {

    let values = try decoder.container(keyedBy: CodingKeys.self)

    table = ((try values.decodeIfPresent(String.self, forKey: .table)))!
    no = (try values.decodeIfPresent(String.self, forKey: .no))!
    rates = (try values.decodeIfPresent([Currency].self, forKey: .rates))!
} }

struct Currency: Codable {
var currency: String
var code: String
var mid: Double

enum CodingKeys: String, CodingKey {
    case currency
    case code
    case mid
}

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)

    currency = try values.decode(String.self, forKey: .currency)
    code = try values.decode(String.self, forKey: .code)
    mid = try values.decode(Double.self, forKey: .mid) 
}
}

在controllerView类中,我编写了两个方法来解析API中的数据

func getLatestRates(){
    guard let currencyUrl = URL(string: nbpApiUrl) else {
        return
    }

    let request = URLRequest(url: currencyUrl)
    let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in

        if let error = error {
            print(error)
            return
        }

        if let data = data {
            self.currencies = self.parseJsonData(data: data)
        }
    })

    task.resume()
}

func parseJsonData(data: Data) -> [Currency] {

    let decoder = JSONDecoder()

    do{
        let currencies = try decoder.decode([String:CurrencyDataStore].self, from: data)

    }
    catch {
        print(error)
    }
    return currencies
}

这段代码不起作用 . 我有这个错误“typeMismatch(Swift.Dictionary,Swift.DecodingError.Context(codingPath:[],debugDescription:”预计会解码字典而是找到一个数组 . “,underlyingError:nil))” .

你可以帮帮我吗?

1 回答

  • 1

    该API返回的JSON为您提供了一个数组,而不是字典,但您告诉JSONDecoder需要一个字典类型 . 将该行更改为:

    let currencies = try decoder.decode([CurrencyDataStore].self, from: data)

相关问题