我试图理解Apple的Codeable函数来解析JSON。我正在youtube上跟随一个教程,这是代码:
.099
当我尝试构建时,我面临6种不同的错误: Error Image
当我从XCode应用建议的修复程序无法解决问题和视频时,此人可以构建这些错误,而没有任何错误。
谁能告诉我我哪里出了问题,或者苹果改变了您使用可编码的方式解析json的方式?
答案 0 :(得分:-1)
根据您的尝试,您的词根是一本有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"
}
}