我正在尝试调用具有字典数组的API:我遇到了以下错误,不确定如何解决。这是我的结构模型
struct Countries : Codable {
var countries : [Country]
}
struct Country : Codable {
var Country : String
var NewConfirmed : Int
var TotalConfirmed : Int
var NewDeaths : Int
var TotalDeaths : Int
var NewRecovered : Int
var TotalRecovered : Int
var CountryCode : String
}
这是我的联网代码:
class Networking {
func response (url: String , completion: @escaping (Countries) -> ()) {
guard let url = URL(string: url) else {return}
URLSession.shared.dataTask(with: url, completionHandler: { (data , response , error ) in
self.urlCompletionHandler(data: data, response: response, error: error, completion: completion)
}).resume()
}
func urlCompletionHandler (data: Data? , response : URLResponse? , error : Error? , completion: (Countries) -> ()) {
guard let data = data else {return}
do {
let jsondecoder = JSONDecoder()
let countries = try jsondecoder.decode(Countries.self, from: data)
completion(countries)
} catch {
print("Error \(error)")
}
}
}
这是我在控制器中的呼叫:
func response () {
newtorkhanler.response(url: UrlPathSingleTon.urlsingleton.shared()) { (countried : (Countries)) in
self.countrizs = countried.countries
DispatchQueue.main.async {
self.tableview.reloadData()
}
}
我想填充一个Country数组,并将其作为Countrys结构中的数组变量填充。我的计划是对国家/地区进行解码,并使用其命名为国家/地区的国家/地区的数组变量并将其设置为响应函数中国家/地区的countrizs
数组。我收到此错误,该错误特定于Countrys结构中的country变量:
错误keyNotFound(CodingKeys(stringValue:“ countries”,intValue: nil),Swift.DecodingError.Context(codingPath:[],debugDescription: “没有与键CodingKeys相关联的值(stringValue:\“ countries \”, intValue:nil)(\“ countries \”)。“,底层错误:nil))
这是API json格式:数组JSON数据在随附的图片中:
{
"Countries": [
{
"Country": "Afghanistan",
"CountryCode": "AF",
"Slug": "afghanistan",
"NewConfirmed": 787,
"TotalConfirmed": 18054,
"NewDeaths": 6,
"TotalDeaths": 300,
"NewRecovered": 63,
"TotalRecovered": 1585,
"Date": "2020-06-05T17:51:15Z"
},
{
"Country": "Albania",
"CountryCode": "AL",
"Slug": "albania",
"NewConfirmed": 13,
"TotalConfirmed": 1197,
"NewDeaths": 0,
"TotalDeaths": 33,
"NewRecovered": 0,
"TotalRecovered": 898,
"Date": "2020-06-05T17:51:15Z"
}
]
}
答案 0 :(得分:1)
要解决此问题,您需要将属性从null
修改为1
。您的密钥应与countries
中的密钥相匹配。
Countries
或者您可以将属性名称更改为小写,将结构名称更改为大写的Swift样式:
JSON
答案 1 :(得分:1)
如果您的var名称与json中的键名称不同,则可以显式定义编码键,以便它们匹配(否则,当所有属性都为Decodable
时,您的编码键将被合成)
struct Countries : Codable {
var countries : [Country]
enum CodingKeys: String, CodingKey {
case countries = "Countries"
}
}
请注意,您的案例必须与您要解码的var的名称匹配。编译器将强制执行此操作,并且当您具有Decodable
枚举中不匹配大小写的属性时,您的对象将不符合CodingKeys
(或Encodable)。
这样,您可以维护命名约定。