簡體   English   中英

JSON解析錯誤-類型'RecentTvListData'沒有下標成員

[英]JSON Parsing error - Type 'RecentTvListData' has no subscript members

我在代碼的shows [“ data”]部分遇到問題,錯誤顯示為'RecentTvListData'類型沒有下標成員 我在底部添加了結構以供參考。

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?
}

由於shows屬性的類型為RecentTvListData ,因此您需要像shows.data這樣進行訪問

小例子:

結構

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")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM