[英]Swift Codable Parsing keyNotFound
我在編碼時遇到了問題。 任何幫助將不勝感激。 我的操場上有以下內容
我的 JSON 文件
{
"metadata": {
"generated": {
"timestamp": 1549331723,
"date": "2019-02-04 20:55:23"
}
},
"data": {
"CA": {
"country-id": 25000,
"country-iso": "CA",
"country-eng": "Canada",
"country-fra": "Canada"
}
}
}
我使用 quicktype 應用程序來幫助生成以下結構
// MARK: - Welcome
struct Welcome: Codable {
let metadata: Metadata?
let data: DataClass?
}
// MARK: - DataClass
struct DataClass: Codable {
let ca: CA
enum CodingKeys: String, CodingKey {
case ca = "CA"
}
}
// MARK: - CA
struct CA: Codable {
let countryID: Int
let countryISO, countryEng, countryFra: String
enum CodingKeys: String, CodingKey {
case countryID = "country-id"
case countryISO = "country-iso"
case countryEng = "country-eng"
case countryFra = "country-fra"
}
}
// MARK: - Metadata
struct Metadata: Codable {
let generated: Generated?
}
// MARK: - Generated
struct Generated: Codable {
let timestamp: Int?
let date: String?
}
SWIFT代碼:
do {
guard let url = Bundle.main.url(forResource: "data", withExtension: "json") else { return 0 }
let jsonData = try Data(contentsOf: url)
let decoder = JSONDecoder()
let data = try decoder.decode(CA.self, from: jsonData)
print (data)
print(data.countryID)
print(data.countryISO)
} catch { print("error" , error) }
這是我收到的錯誤消息。
jsonData 244 bytes
error keyNotFound(CodingKeys(stringValue: "country-id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"country-id\", intValue: nil) (\"country-id\").", underlyingError: nil))
價值就在那里,我不確定問題是什么。 如果我從 json 和模型中刪除 country-id,我會收到與 country-iso 相同的錯誤。
那是因為您試圖解碼錯誤的類型。 CA
類型在您的 JSON 中嵌套了多個級別,您需要將根類型傳遞給JSONDecoder.decode
。
let root = try decoder.decode(Welcome.self, from: jsonData)
guard let ca = root.data?.ca else { return 0 }
print(ca)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.