簡體   English   中英

沒有與鍵 CodingKeys 錯誤關聯的值

[英]No value associated with key CodingKeys error

我正在嘗試從谷歌圖書 api 中檢索 json

這是我的結構:

struct Book: Codable {
    let volumeInfo: VolumeInfo
}

struct VolumeInfo: Codable {
    let title: String
    let authors: [String]
    let publisher, publishedDate, description: String
    
}

這是解碼我的 json 的代碼:

     var bookInfo = [Book]()

    override func viewDidLoad() {
        super.viewDidLoad()
        if let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=harry+potter") {

            URLSession.shared.dataTask(with: url) { data, response, error in
                if let data = data {
                    do {  
                        let parsedJSON = try JSONDecoder().decode(Book.self, from: data)
     
                        for books in self.bookInfo {
                            DispatchQueue.main.async {
                                print(books.volumeInfo.title)
                            }
                       }
                   } catch {
                       print(error)
                   }
               }
           }.resume()
            
        }       

}

我得到的錯誤信息是這樣的:

keyNotFound(CodingKeys(stringValue: "volumeInfo", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "volumeInfo", intValue: nil) ("volumeInfo" )。”,基礎錯誤:無))

您正在嘗試解碼Book object,您應該在其中解碼 API 響應,然后從中提取圖書。 這就是您收到錯誤的原因。

試試下面的示例代碼:

struct Book: Identifiable, Codable {
    let id = UUID()
    let volumeInfo: VolumeInfo
}

struct VolumeInfo: Codable {
    let title, publishedDate: String
    let authors: [String]?
    let publisher, description: String?
    
}

struct ApiResponse: Codable {
    let kind: String
    let totalItems: Int
    let items: [Book]
}





var bookInfo = [Book]()

override func viewDidLoad() {
    super.viewDidLoad()
    if let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=harry+potter") {
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data {
                do {
                    let response = try JSONDecoder().decode(ApiResponse.self, from: data)
                    bookInfo = response.items
                } catch {
                    print(error)
                }
            }
        }.resume()
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM