无法使用 Codeable 解析 JSON

Unable to Parse JSON With Codeable

我正在尝试理解 Apple 的 Codeable 函数来解析 JSON。我正在关注 youtube 上的教程,这是代码:

override func viewDidLoad() {
    super.viewDidLoad()

    struct Forex: Decodable {
        let open: Int?
        let close: Int?
        let high: Int?
    }

    let jsonUrlString = "https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=EUR&to_symbol=USD&interval=5min&apikey=demo"

    let urlObj = URL(string: jsonUrlString)

    URLSession.shared.dataTask(with: urlObj!) {(data, response, error)} in

    do {
        let forex = try JSONDecoder().decode([Forex].self, from: data)

    } catch {


    }

当我尝试构建时,我遇到了 6 个不同的错误: Error Image

当我应用 XCode 中建议的修复程序时,它没有解决问题和视频,此人能够使用 none 这些错误进行构建。

谁能告诉我哪里出了问题,或者 apple 是否更改了您使用 codeable 解析 json 的方式?

根据您的尝试,您的根是一个包含 2 个键的字典,您需要 timeSeriesFX5Min

class VCName:UIViewController {
   override func viewDidLoad() {
     super.viewDidLoad() 

    let jsonUrlString = "https://www.alphavantage.co/query?function=FX_INTRADAY&from_symbol=EUR&to_symbol=USD&interval=5min&apikey=demo"

    let urlObj = URL(string: jsonUrlString)

    URLSession.shared.dataTask(with: urlObj!) {(data, response, error) in
     guard let data = data else { return }  
    do {
        let forex = try JSONDecoder().decode(Root.self, from: data)
        print(forex.timeSeriesFX5Min)
    } catch {

        print(error)
    }

    }.resume()
  }
}       


struct Root: Codable { 
    let timeSeriesFX5Min: [String:Forex]

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


// MARK: - TimeSeriesFX5Min
struct Forex: Codable {
    let the1Open, the2High, the3Low, the4Close: String

    enum CodingKeys: String, CodingKey {
        case the1Open = "1. open"
        case the2High = "2. high"
        case the3Low = "3. low"
        case the4Close = "4. close"
    }
}