No value associated with key CodingKeys 错误

No value associated with key CodingKeys error

我正在尝试从 google 本书中检索 json api

这是我的结构:

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").", underlyingError: nil))

您正在尝试解码一个 Book 对象,您应该在其中解码 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()
    }
}