且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我不知道字典的键时,如何从JSON解码字典?

更新时间:2023-01-04 22:23:10

您只需创建自己的StockValue模型,例如

You an simply create your Stock and Value models like,

struct Stock: Decodable {
    let timeSeries: [String:Value]

    enum CodingKeys: String, CodingKey {
        case timeSeries = "Time Series (5min)"
    }
}

struct Value: Decodable {
    let open: String
    let high: String
    let low: String
    let close: String
    let volume: String

    enum CodingKeys: String, CodingKey{
        case open = "1. open"
        case high = "2. high"
        case low = "3. low"
        case close = "4. close"
        case volume = "5. volume"
    }
}

不需要单独的struct Function.

使用JSONDecoder之类的解析您的回复,

Parse your response using JSONDecoder like,

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