json - Swift 解码嵌套的 JSON

标签 json swift decode codable

我在解析来自 NBP api“http://api.nbp.pl/api/exchangerates/tables/a/?format=json”的数据时遇到问题。我创建了结构 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 类中,我编写了 2 个方法来解析来自 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: “Expected to decode Dictionary but found an array instead.”, underlyingError: nil))”。

你能帮帮我吗?

最佳答案

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

让 currencys = try decoder.decode([CurrencyDataStore].self, from: data)

关于json - Swift 解码嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957045/

相关文章:

c# - 当对象继承自列表时序列化对象

json - Firebase 不断更改 JSON 文件

java - JSON 教程/常见问题解答/示例/基础知识

ios - 如何在不暴露私有(private)函数的情况下在单元测试中操作核心数据?

分块传输解码器,C 代码片段

javascript - 无法在 Python 中解码来自 Javascript 的 JSON 响应

ios - 如何删除 UIStackView 中两个 tableview 之间的空间?

swift - 检查是否从 Swift 中的 UILocalNotification 启动

javascript - 一种解码 HTML 实体的简单 JavaScript 方法,适用于浏览器和 Node

c - 需要二维数组帮助的前向纠错