集合视图单元的JSON解码错误

时间:2018-04-10 16:06:55

标签: ios json swift uicollectionview decodable

我正在尝试在Xcode 9.2,Swift 4中构建一个iOS应用程序,它使用Collection View Cell来显示JSON文件中的每个类别。我正在通过本教程作为示例 - https://www.youtube.com/watch?v=hPJaQ2Fh7Ao,但我收到一个错误:

typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“预计会解码数组,但会找到一个字典。”,underlyingError:nil))

我尝试了几种不同的东西,但是我被困住了(对此我不熟悉)。关于我遗失或做错的任何建议都会很棒。谢谢!

JSON API:

{
  "category": [
    {
      "id": 216,
      "title": "Spring"
    },
    {
      "id": 219,
      "title": "Earth Day"
    },
    {
      "id": 114,
      "title": "Admin. Professionals' Day"
    }
  ]
}

ViewController.swift:

import UIKit

struct Category: Codable {
    let category: [CategoryItem]
}

struct CategoryItem: Codable {
    let id: Int
    let title: String

    enum CodingKeys: String, CodingKey {
        case id, title
    }
}

class ViewController: UIViewController, UICollectionViewDataSource {

    var categories = [Category]()

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self

        let jsonUrlString = "https://apis.*************/***/****/********"
        guard let url = URL(string: jsonUrlString) else { return }

        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else { return }

            if err == nil {
                do {
                    let decoder = JSONDecoder()
                    let ecardcategory = try decoder.decode([Category].self, from: data)
                    self.categories = ecardcategory
                } catch let err {
                    print("Err", err)
                }

                DispatchQueue.main.async {
                    //print(self.categories.count)
                    self.collectionView.reloadData()
                }
            }
        }.resume()

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return categories.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as? CustomCollectionViewCell
        //cell?.nameLbl.text = categories[indexPath.row].title
        return cell!
    }
}

1 个答案:

答案 0 :(得分:1)

错误

  

“预计会对Array进行解码,但会找到一个字典。”

非常清楚:根对象是一个字典(由{}表示),所以删除括号。

let ecardcategory = try decoder.decode(Category.self, from: data)

您必须声明数据源数组

var categories = [CategoryItem]()

并填充

self.categories = ecardcategory.category