Ios 试图解码来自Youtube Api的数据在swift getting中流行的视频;预计将解码阵列<;任何>;但却找到了一本字典;

Ios 试图解码来自Youtube Api的数据在swift getting中流行的视频;预计将解码阵列<;任何>;但却找到了一本字典;,ios,json,swift,codable,Ios,Json,Swift,Codable,我是swift新手,正在学习将数据从Api解析到我的swift应用程序。 我试图从Youtube流行视频的APi获取数据:()但我无法获取数据,不知道哪里出错了。但它的给出“期望解码数组,但却找到了一个字典。” 这是我的模型: struct Items: Codable { let kid : String } struct PopularVideos: Codable, Identifiable { let id: String? let kin

我是swift新手,正在学习将数据从Api解析到我的swift应用程序。 我试图从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&regionCode=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()
}

该API调用返回的根对象不是数组。它是一个包含
项的数组的简单对象

那么,你想要什么

let tempYTVideos = try JSONDecoder().decode(PopularVideos.self, from: data!)
而且,您的数据结构看起来不正确;根对象中没有
id
属性,项中没有
kid
属性。项目具有
种类
id

我还建议您将结构命名为
,而不是
,因为它代表单个项

struct Item: Codable, Identifiable {
    
    let kind: String
    let id: String
}


struct PopularVideos: Codable {
    
    let kind : String
    let items : [Item]
}

您是否验证了来自API的json是否正确?