【发布时间】:2020-11-09 20:06:17
【问题描述】:
我有 3 个不同的 URL 用于获取我的 JSON:2 个使用“sn-p”参数,1 个不使用。第三个崩溃告诉我它没有“sn-p”参数,但前两个没有“统计”参数并且不会崩溃?
网址 1:“https://www.googleapis.com/youtube/v3/search?part=sn-p&channelId=(channelID)&maxResults=10&order=viewCount&key=(Constant.API_KEY)”
网址 2:“https://www.googleapis.com/youtube/v3/channels?part=sn-p&forUsername=(channelName)&key=(Constant.API_KEY)”
网址 3:“https://www.googleapis.com/youtube/v3/videos?part=statistics&id=(videoID)&key=(Constant.API_KEY)”
值得注意的是,我已经确认我正在获取 JSON,但它只是在涉及模型时崩溃。
struct Video: Identifiable, Decodable {
var id = UUID()
var title = ""
var thumbnail = ""
var videoID = ""
var publishedDate = ""
var youtuber = ""
var viewCount = ""
var watched = false
enum CodingKeys: String, CodingKey {
case snippet
case thumbnails
case high
case id
case statistics
case videoID = "videoId"
case title
case thumbnail = "url"
case publishedDate = "publishedAt"
case youtuber = "channelTitle"
case viewCount
}
init (from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let snippetContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .snippet)
let thumbnailsContainer = try snippetContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .thumbnails)
let highContainer = try thumbnailsContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .high)
let idContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .id)
let statisticsContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .statistics)
self.title = try snippetContainer.decode(String.self, forKey: .title)
self.thumbnail = try highContainer.decode(String.self, forKey: .thumbnail)
self.videoID = try idContainer.decode(String.self, forKey: .videoID)
self.publishedDate = try snippetContainer.decode(String.self, forKey: .publishedDate)
self.youtuber = try snippetContainer.decode(String.self, forKey: .youtuber)
self.viewCount = try statisticsContainer.decode(String.self, forKey: .viewCount)
}
}
Solution:
Used the “if container.contains(CodingKeys.statistics)” method, problem solved.
【问题讨论】:
-
您需要提供一个可重现性最低的示例,否则会导致您在下面的答案中看到的那种来回。您收到的 JSON 有哪些变化(请从 JSON/模型中删除任何不相关的内容)
标签: json swift enums decodable