json - 为什么某些变量为零?
问题描述
我正在尝试解码此 json,但某些变量为零。其中大多数似乎还可以,只是其中一些无法正常工作。我对 swift 没有太多经验,所以我有点不知道下一步该尝试什么。
我的代码:
struct Attr : Decodable {
let page: String?
let perpage: String?
let totalpages: String?
let total: String?
}
struct Images : Decodable {
let text: String?
let size: String?
}
struct Artist : Decodable {
let name: String?
let mbid: String?
let url: String?
}
struct Streamable : Decodable {
let text: String?
let fulltrack: String?
}
struct Track : Decodable {
let name: String?
let duration: String?
let playcount: String?
let listeners: String?
let mbid: String?
let url: String?
let streamable: Streamable?
let artist: Artist?
let images: [Images]?
}
struct Tracks : Decodable {
let track:[Track]?
}
struct Container : Decodable {
let tracks: Tracks?
let attr: Attr?
}
json:
{
"tracks": {
"track": [
{
"name": "bad guy",
"duration": "0",
"playcount": "870682",
"listeners": "125811",
"mbid": "",
"url": "https://www.last.fm/music/Billie+Eilish/_/bad+guy",
"streamable": {
"#text": "0",
"fulltrack": "0"
},
"artist": {
"name": "Billie Eilish",
"mbid": "",
"url": "https://www.last.fm/music/Billie+Eilish"
},
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/88d7c302d28832b53bc9592ccb55306b.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/88d7c302d28832b53bc9592ccb55306b.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/88d7c302d28832b53bc9592ccb55306b.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/88d7c302d28832b53bc9592ccb55306b.png",
"size": "extralarge"
}
]
},
...
images 应该包含一个图像数组而不是 nil,尽管大多数其他变量似乎没问题
解决方案
添加 CodingKey 枚举以映射名称中带有 # 的字段
struct Images : Decodable {
let text: String?
let size: String?
enum CodingKeys: String, CodingKey {
case text = "#text"
case size
}
}
struct Streamable : Decodable {
let text: String?
let fulltrack: String?
enum CodingKeys: String, CodingKey {
case text = "#text"
case fulltrack
}
}
您的Track
结构中也有错误,请更改images
为image
(或使用 CodingKey 映射到那里)。有关解码 json 的更多信息,请参阅Apple 的文档
推荐阅读
- protractor - 使用量角器提取下拉列表中的元素
- json - 查找并执行文件 whit()
- php - 上传大文件和超时 php 上传
- java - 在单个方法中创建和使用 ArrayList?
- laravel - 如何在 laravel 中设置默认语言
- wpf - Popover 应在延迟 0.3 秒后打开(Popover 是从 Popup 派生的 WPF 自定义控件)
- java - javac 的 --module-path 的合法路径是什么?
- r - ggplot2 - 将分割线添加到矩阵图中
- django - Django ImageField 无法处理 tif 图像
- python - 减少pytorch中的批量大小