我正在尝试从下面的 API 解码 API,但我仍然收到以下错误:
keyNotFound(CodingKeys(stringValue: "resources", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "resources", intValue: nil)], debugDescription: "No value with key CodingKeys(stringValue: \"resources\", intValue: nil) (\"resources\").", underlyingError: nil))
API 地址:https://age-of-empires-2-api.herokuapp.com/docs/
我已经多次尝试查看我的结构,并在 API 的不同级别中尝试调用代码,但仍然无法获取数据。我还尝试使用 print(resources.XXX) 格式从不同级别调用对象。
这是我第一次从 API 调用数据:
{
"resources": {
"civilizations": "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations",
"units": "https://age-of-empires-2-api.herokuapp.com/api/v1/units",
"structures": "https://age-of-empires-2-api.herokuapp.com/api/v1/structures",
"technologies": "https://age-of-empires-2-api.herokuapp.com/api/v1/technologies"
}
}
这些是结构的前两个级别:
// MARK: - Resources
struct Resources: Codable {
let resources: [String : ResourcesList]
enum CodingKeys: String, CodingKey {
case resources
}
}
// MARK: - ResourcesList
struct ResourcesList: Codable {
let civilizations: CivilizationList
let units: UnitList
let structures: StructureList
let technologies: TechnologyList
enum CodingKeys: String, CodingKey {
case civilizations, units, technologies, structures
}
}
在这些结构下面,我已经实现了API网站中指示的模型,例如CivilizationList,Civilization等。
这是我的电话代码:
let jsonUrl = "https://age-of-empires-2-api.herokuapp.com/api/v1"
guard let url = URL(string: jsonUrl) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
let dataAsString = String(data: data, encoding: .utf8)
do {
let decoder = JSONDecoder()
let resources = try decoder.decode([String : Resources].self, from: data)
print(resources)
} catch {
print(error)
}
print(dataAsString!)
}.resume()
我已经在这里查看了所有其他关于相同错误代码的线程,尝试了一些东西,但是我可能缺少一些非常基本的东西,不幸的是,我太初学者了,没有注意到它。任何帮助,不胜感激。
模型应该是
// MARK: - Empty
struct Resources: Codable {
let resources: ResourcesList
}
// MARK: - Resources
struct ResourcesList: Codable {
let civilizations, units, structures, technologies: String
}
解码
let resources = try decoder.decode(Resources.self, from: data)
因为civilizations, units, structures, technologies
是字符串而不是模型
或
let resources = try decoder.decode([String : ResourcesList].self, from: data)