【发布时间】:2021-11-05 15:52:55
【问题描述】:
你好,我有一个像这样的 json 文件
}
"CYYZ": {
"icao": "CYYZ",
"iata": "YYZ",
"name": "Lester B. Pearson International Airport",
"city": "Toronto",
"state": "Ontario",
"country": "CA",
"elevation": 569,
"latitude": 43.6772003174,
"longitude": -79.6305999756,
"tz": "America\/Toronto"
},
"CYZD": {
"icao": "CYZD",
"iata": "YZD",
"name": "Downsview Airport",
"city": "Toronto",
"state": "Ontario",
"country": "CA",
"elevation": 652,
"latitude": 43.7425003052,
"longitude": -79.4655990601,
"tz": "America\/Toronto"
},
"CYZE": {
"icao": "CYZE",
"iata": "YZE",
"name": "Gore Bay Manitoulin Airport",
"city": "Gore Bay",
"state": "Ontario",
"country": "CA",
"elevation": 635,
"latitude": 45.8852996826,
"longitude": -82.5678024292,
"tz": "America\/Toronto"
}
}
我做了一个这样的结构
struct AirportData: Codable{
let iata: String
let name: String
let longitude: Double
let latitude: Double
}
我编写了以下代码来设置 url 并使其成为字符串,然后我用它来解码 json
override func viewDidLoad() {
super.viewDidLoad()
//make url for file path
guard let jsonURL = Bundle(for: type(of: self)).path(forResource: "airports", ofType: "json") else {
return
}
//make url a string
guard let jsonString = try? String(contentsOf: URL(fileURLWithPath:jsonURL), encoding: String.Encoding.utf8) else {
return
}
var airports: AirportData?
do{
airports = try JSONDecoder().decode(AirportData.self, from: Data(jsonString.utf8))
}
catch{
print("error occured when decoding")
}
guard let results = airports else {
return
}
print(results.iata)
}
我不断收到“解码时出错”
请帮助我遵循this 教程,但没有得到相同的结果,也许我的结构是错误的。谢谢。
【问题讨论】: