尝试从API获取数据时出现“与键CodingKeys没有关联的值”错误-Swift

时间:2020-09-04 00:41:54

标签: swift cs50

嗨,我正在尝试制作一个pokedex应用程序,我以前在我的代码中使用了相同的API并成功了,但是现在当我从API调用另一个链接时,我得到了此错误:

keyNotFound(CodingKeys(stringValue: "root", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"root\", intValue: nil) (\"root\").", underlyingError: nil))

我正在尝试描述神奇宝贝。 这是我目前无法使用的代码:

func loadFlavor() {
    guard let url = URL(string: "https://pokeapi.co/api/v2/pokemon-species/1/") else {
        return
    }
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else {
            return
            }
        
        do {
            let result = try JSONDecoder().decode(SpeciesResults.self, from: data)
            DispatchQueue.main.async {
                for typeEntry in result.root
                {
                    self.descriptionText.text = typeEntry.flavor_text_entries.flavor_text
                }
            }
        }
        catch let error {
            print(error)
        }
    }.resume()
}

这些是我的结构:

struct SpeciesResults: Codable {
    let root: [PokemonFlavorResults]
}
struct PokemonFlavorResults: Codable {
    let flavor_text_entries: Zerodic
}
struct Zerodic: Codable {
    let flavor_text: String
}

1 个答案:

答案 0 :(得分:0)

问题:

  1. 您不需要SpeciesResults模型,因为flavor_text_entries对象已经在根级别。

  2. 使用驼峰式大小写来定义变量。在Codable中,您可以将convertFromSnakeCase用作decoder's keyDecodingStrategy

解决方案:

因此,Codable模型必须是

struct PokemonFlavorResults: Codable {
    let flavorTextEntries: [Zerodic]
}
struct Zerodic: Codable {
    let flavorText: String
}

并像这样解析 JSON data

do {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let results = try decoder.decode(PokemonFlavorResults.self, from: data)
    //use results here...
} catch {
    print(error)
}