问题描述
我在编码方面遇到了问题。任何帮助将不胜感激。我的操场上有以下物品
我的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?
}
快捷代码:
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)