我一直收到一个keyNotFound编码密钥错误



我正在使用谷歌图书api,我一直收到这个错误:

keyNotFound(编码键(字符串值:"industryIdentifiers",intValue:nil(,Swift。DecodingError.Context(编码路径:[CodingKeys(字符串值:"项目";,intValue:nil(,_JSONKey(字符串值:"索引2",intValue:2( ,CodingKeys(字符串值:"volumeInfo",intValue:nil(],debugDescription:";没有与键关联的值编码键(字符串值:"industryIdentifiers",intValue:nil(("行业标识符"(&";,underlyingError:nil((

这些是我的结构:

struct Book: Identifiable, Codable {
let id = UUID()
let volumeInfo: VolumeInfo
}
struct VolumeInfo: Codable {
let title, publishedDate: String?
let authors: [String]?
let publisher, description: String?
let imageLinks: ImageLinks?
let industryIdentifiers: [IndustryIdentifier]
let averageRating: Double?
let id: String?
}
// MARK: - IndustryIdentifier
struct IndustryIdentifier: Codable {
let identifier: String
}
struct ApiResponse: Codable {
let kind: String
let totalItems: Int
let items: [Book]
}
struct ImageLinks: Codable {
let smallThumbnail, thumbnail: String
}

我就是这样称呼它的:

override func viewDidLoad() {
super.viewDidLoad()

var searchText = "the+deal"
searchBooks()

}
func searchBooks() {
if let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=(searchText)") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
let response = try JSONDecoder().decode(ApiResponse.self, from: data)
self.bookInfo = response.items

} catch {
print(error)
}

}
DispatchQueue.main.async {
self.tableview.reloadData()
}

}.resume()
}
}

似乎industryIdentifiers是一个可选值

let industryIdentifiers: [IndustryIdentifier]?

应该解决这个问题。

最新更新