首页 > 解决方案 > 预计解码数组而是找到了一本字典。”

问题描述

当我尝试解析volumeInfo. 我能够检索totalItems,如果我在struct 中省略id,但是当我在struct 中添加时,解析不会发生,我收到上述错误。etagvar volumeInfo: [VolumeInfo]?Itemsvar volumeInfo: [VolumeInfo]?Items

这是我的 JSON 响应数据:

{
    "kind": "books#volumes",
    "totalItems": 2361,
    "items": [
        {
            "kind": "books#volume",
            "id": "_eyJAAAAQBAJ",
            "etag": "MJbx6HKC3B4",
            "selfLink": "https://www.googleapis.com/books/v1/volumes/_eyJAAAAQBAJ",
            "volumeInfo": {
                "title": "A Quilting Life",
                "subtitle": "Creating a Handmade Home",
                "authors": [
                    "Sherri McConnell"
                ],
                "publisher": "C&T Publishing Inc",
                "publishedDate": "2013-02-12",
                "description": "Bring the handmade tradition home with these charming quilts and home accessories. Inspired by a grandmother who loved to sew for her family, quilter and blogger Sherri McConnell gives traditional patterns like hexagons, stars, snowballs, and Dresden Plates a new look featuring fabrics by some of today’s most popular designers. 19 cozy projects include pillows, tote bags, table runners, and larger quilts—quick and easy designs that make great gifts.",

数据模型:

struct Book: Codable {
    var totalItems:Int = 0
    var items:[Items]?
}

struct Items: Codable {
    var id: String?
    var etag: String?
    var volumeInfo: [VolumeInfo]?
}

struct VolumeInfo: Codable {
    var authors: String?
    var categories: String?
    var description: String
    var pageCount: Int?
    var publishedDate: String?
    var publisher: String?
    var subtitle: String?
    var title: String?
}

import UIKit

class ViewController: UIViewController {
    let urlString = "https://www.googleapis.com/books/v1/volumes?q=quilting"
    var items: [Items] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let url = URL(string: urlString)
        guard url != nil else {
            return
        }

        let session = URLSession.shared

        let dataTask = session.dataTask(with: url!) { [self] (data, response, error) in
            //check for errors
            if error == nil && data != nil{

                //parse json
                let decorder = JSONDecoder()
                do {
                    let bookInfo = try decorder.decode(Book.self, from: data!)
                    items = bookInfo.items!
                    print("Retrieved books are \(items)")
                }
                catch {
                    print("Error in json parcing\(error)")
                }
            }
        }
        //make api call
        dataTask.resume()
    }
}

标签: jsonswiftparsingcodable

解决方案


推荐阅读