我遇到了 show [“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?
}
答案 0 :(得分:1)
显示属性属于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")
}