JSON 解析错误 - 类型"最近电视列表数据"没有下标成员



我在 show [" data"] 中遇到问题。我添加了底部的结构以供参考。

URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard let data = data else {return}
        do {
            let shows =  try
                JSONDecoder().decode(RecentTvListData.self, from: data)
            print(shows)
            self.tvShows = [RecentTvList]()
            if let array = shows["data"] as? [[String: Any]] {
                for dictionary in array {
                var tvShow = RecentTvList()
                    tvShow.title = dictionary["title"] as? String
                    tvShow.poster_url = dictionary["poster_url"] as? String
                    self.tvShows?.append(tvShow)
                }
            }
        } catch let jsonErr {
            print("Error serializing JSON", jsonErr)
        }
    }.resume()
struct RecentTvListData: Decodable  {
    var data: [RecentTvList]
}
struct RecentTvList: Decodable  {
    var title: String?
    var poster_url: String?
}

show 属性是RecentTvListData类型,因此您需要像shows.data

一样访问

小例子:

structs

struct RecentTvList: Decodable  {
    var title: String?
    var poster_url: String?
    // Custom keys for poster_url
    enum CodingKeys: String, CodingKey {
        case title
        case poster_url = "poster_url"
    }
}
struct RecentTvListData: Decodable  {
    var data: [RecentTvList]
}

没有循环

var tvShows: [RecentTvList] = []
do {
    let shows = try JSONDecoder().decode(RecentTvListData.self, from: data)
    tvShows = shows.data
} catch {
    debugPrint("Error")
}

带有循环

var tvShows: [RecentTvList] = []
do {
    let shows = try JSONDecoder().decode(RecentTvListData.self, from: data)
    for item in shows.data {
        var tvShow = RecentTvList()
        tvShow.title = item.title
        tvShow.poster_url = item.poster_url
        tvShows.append(tvShow)
    }
} catch {
    debugPrint("Error")
}

最新更新