ios - JSON解码失败
问题描述
我正在尝试快速解码来自 youtube API 的 JSON 响应。
JSON信息是:
我做了一个可解码的结构:
// Build a model object to import the JSON data.
struct PlaylistInformation: Decodable {
struct Items: Decodable {
struct VideoNumber: Decodable {
struct Snippet: Decodable {
let title: String
}
let snippet: Snippet
}
let videoNumber: VideoNumber
}
let items: Items
}
尝试解码时出现错误:
// We decode the JSON data get from the url according to the structure we declared above.
guard let playlistInformation = try? JSONDecoder().decode(PlaylistInformation.self, from: data!) else {
print("Error: could not decode data into struct") <-- HERE IS THE ERROR
return
}
// Comparing DB Versions.
let videoTitle = playlistInformation.items.videoNumber.snippet.title as NSString
print(videoTitle)
我得到的错误是:
Error: could not decode data into struct
我想它与结构中的“项目”有关,因为它是一个数组......但我不知道如何解决这个问题。
解决方案
鉴于这items
是一个数组,您必须将其建模为数组而不是结构:
// Build a model object to import the JSON data.
struct PlaylistInformation: Decodable {
struct Item: Decodable {
struct Snippet: Decodable {
let title: String
}
let snippet: Snippet
}
let items: [Item]
}
然后使用其索引访问每个项目,例如
let videoTitle = playlistInformation.items[0].snippet.title as NSString
print(videoTitle)
推荐阅读
- cakephp - CakePHP 3.8 - Cookie 删除
- android - Android Smack 4.2 如何上传文件?
- python - TensorFlow 2 中可以用什么代替 tf.train.GradientDescentOptimizer
- c# - 独立于 ISS 范围调度后台作业
- keras - 深度学习,奇怪的批量标准化
- flutter - 在 performLayout() 期间抛出 PageView NoSuchMethodError
- javascript - Bootstrap Accordion - 一次一个活跃的班级
- html - 如何使用 SP.UI.ModalDialog.ShowPopupDialog() 函数来弹出一个 img(Sharepoint)?
- typescript - 字典上的奇怪错误“对象可能是'未定义'”
- javascript - 如何在 React 中播放来自 blob 对象的音频?