我如何使用可编码解码字典数组

问题描述 投票:0回答:2

我正在尝试调用具有字典数组的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结构内的countrys变量:

错误keyNotFound(CodingKeys(stringValue:“ countries”,intValue: nil),Swift.DecodingError.Context(codingPath:[],debugDescription: “没有与关键字CodingKeys相关联的值(stringValue:\“ countries \”, intValue:nil)(\“ countries \”)。“,底层错误:nil))]

这是API json格式:数组JSON数据在随附的图片中:

json data pic

{
    "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"
        }
    ]
}
json swift codable
2个回答
1
投票

要解决此问题,您需要将属性从countries修改为Countries。您的键应与JSON中的键匹配。

struct Countries : Codable {
    var Countries : [Country]
}

或者您可以将属性名称设置为小写,将结构名称设置为大写的Swift样式,如下所示:

struct Countries : Codable {
    var countries : [Country]
    enum CodingKeys: String, CodingKey {
         case countries = "Countries"
    }
}

1
投票

如果您的var名称与json中的键名称不同,则可以显式定义编码键,以便它们匹配(否则,当所有属性都为Decodable时,将合成您的编码键。

struct Countries : Codable {
    var countries : [Country]

    enum CodingKeys: String, CodingKey {
         case countries = "Countries"
    }
}

请注意,您的案例必须与您要解码的var的名称匹配。编译器将强制执行此操作,并且当您具有Decodable枚举中不匹配大小写的属性时,您的对象将不符合CodingKeys(或Encodable)。

这样,您可以维护您的命名约定。

© www.soinside.com 2019 - 2024. All rights reserved.