如何在 Swift 中仅从复杂的 JSON(Google 书籍 API)中获取某些值

How to fetch only certain values from a complex JSON (Google Books API) in Swfit

我一直在尝试开发一个应用程序,它从 Google Books API 中获取一本书的某些信息(名称、作者和图像)并在集合视图中显示图像

var bookInfo = [Book]()

let urlString = "https://www.googleapis.com/books/v1/volumes/J8ahqXjUhAAC"

    

override func awakeFromNib() {
    super.awakeFromNib()
    collectionView.delegate = self
    collectionView.dataSource = self
    
    let url = URL(string: urlString)
    
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        do {
            self.bookInfo = try JSONDecoder().decode([Book].self, from: data!)
            for info in self.bookInfo {
                print(info.bookName)
            }
        }
        catch {
            print("error")
        }
    }
    
}

下面是一个结构,它表示我要捕获的内容,但不确定这是否完全正确。

struct Book: Codable {
    var bookName: String
    var imageURL: String
    var pageCount: Int
    var author: String
    var format: String
}


struct volumeInfo: Codable {
    var bookInfo: [Book]
}

当 运行 这段代码时,我没有收到任何错误,但应用程序无法获取任何内容,我的 UIImageView 是空的。

您正在使用的 Book 结构不起作用,因为它与 JSON 响应不匹配。这是整个结构,但是,您可以删除不需要的键(属性),它仍然可以工作:

struct Book: Codable {
    let kind, id, etag, selfLink: String
    let volumeInfo: VolumeInfo
    let saleInfo: SaleInfo
    let accessInfo: AccessInfo
}

struct AccessInfo: Codable {
    let country, viewability: String
    let embeddable, publicDomain: Bool
    let textToSpeechPermission: String
    let epub, pdf: Epub
    let webReaderLink, accessViewStatus: String
    let quoteSharingAllowed: Bool
}

struct Epub: Codable {
    let isAvailable: Bool
}

struct SaleInfo: Codable {
    let country, saleability: String
    let isEbook: Bool
}

struct VolumeInfo: Codable {
    let title: String
    let authors: [String]
    let publisher, publishedDate, description: String
    let industryIdentifiers: [IndustryIdentifier]
    let readingModes: ReadingModes
    let pageCount, printedPageCount: Int
    let dimensions: Dimensions
    let printType: String
    let categories: [String]
    let averageRating: Double
    let ratingsCount: Int
    let maturityRating: String
    let allowAnonLogging: Bool
    let contentVersion: String
    let panelizationSummary: PanelizationSummary
    let imageLinks: ImageLinks
    let language, previewLink, infoLink, canonicalVolumeLink: String
}

struct Dimensions: Codable {
    let height, width, thickness: String
}

struct ImageLinks: Codable {
    let smallThumbnail, thumbnail: String
}

struct IndustryIdentifier: Codable {
    let type, identifier: String
}

struct PanelizationSummary: Codable {
    let containsEpubBubbles, containsImageBubbles: Bool
}

struct ReadingModes: Codable {
    let text, image: Bool
}