我是swift的新手,我正在学习如何将数据从Api解析到我的Swift应用程序。我试着从流行视频(https://developers.google.com/youtube/v3/docs/videos/list)的Youtube APi上获取数据,但我无法获取数据,不知道我哪里搞错了。但是它给出了“期望解码数组,但却找到了一个字典”。
这是我的模型:
struct Items: Codable {
let kid : String
}
struct PopularVideos: Codable, Identifiable {
let id: String?
let kind : String
let items : [Items]
}我的Api请求方法:
//Getting Api calls for youtube video
func getYoutubeVideo(){
let url = URL(string: "https://www.googleapis.com/youtube/v3/videos?part=snippet&chart=mostPopular®ionCode=US&key=\(self.apiKey)")!
URLSession.shared.dataTask(with: url){(data, response, error) in
do {
let tempYTVideos = try JSONDecoder().decode([PopularVideos].self, from: data!)
print(tempYTVideos)
DispatchQueue.main.async {
self.YTVideosDetails = tempYTVideos
}
}
catch {
print("There was an error finding data \( error)")
}
} .resume()
}发布于 2020-10-08 07:39:48
该API调用返回的根对象不是数组。它是一个包含Item数组的简单对象。
所以,你想
let tempYTVideos = try JSONDecoder().decode(PopularVideos.self, from: data!)此外,您的数据结构看起来不正确;根对象中没有id属性,项中也没有kid属性。一个项目有一个kind和一个id。
我还建议您将结构命名为Item而不是Items,因为它表示单个项;
struct Item: Codable, Identifiable {
let kind: String
let id: String
}
struct PopularVideos: Codable {
let kind : String
let items : [Item]
}https://stackoverflow.com/questions/64253515
复制相似问题