我有以下JSON字符串要解码:
{
"albums": {
"album": [
{
"name": "Dark & Wild",
"mbid": "",
"url": "https://www.last.fm/music/BTS",
"artist": {
"name": "BTS",
"mbid": "0d79fe8e-ba27-4859-bb8c-2f255f346853",
"url": "https://www.last.fm/music/BTS"
},
"image": [
{
"#text": "https://lastfm.freetls.fastly.net/i/u/34s/6dfcd9efe7f9560334eadaf3ad6a0049.png",
"size": "small"
},
{
"#text": "https://lastfm.freetls.fastly.net/i/u/64s/6dfcd9efe7f9560334eadaf3ad6a0049.png",
"size": "medium"
},
{
"#text": "https://lastfm.freetls.fastly.net/i/u/174s/6dfcd9efe7f9560334eadaf3ad6a0049.png",
"size": "large"
},
{
"#text": "https://lastfm.freetls.fastly.net/i/u/300x300/6dfcd9efe7f9560334eadaf3ad6a0049.png",
"size": "extralarge"
}
],
"@attr": {
"rank": "1"
}
},
{
"name": "Agust D",
"mbid": "",
"url": "https://www.last.fm/music/Agust+D",
"artist": {
"name": "Agust D",
"mbid": "",
"url": "https://www.last.fm/music/Agust+D"
},
"image": [
{
"#text": "https://lastfm.freetls.fastly.net/i/u/34s/05ed3fae3b45b2fcda6c80e76c4c8aed.png",
"size": "small"
},
{
"#text": "https://lastfm.freetls.fastly.net/i/u/64s/05ed3fae3b45b2fcda6c80e76c4c8aed.png",
"size": "medium"
},
{
"#text": "https://lastfm.freetls.fastly.net/i/u/174s/05ed3fae3b45b2fcda6c80e76c4c8aed.png",
"size": "large"
},
{
"#text": "https://lastfm.freetls.fastly.net/i/u/300x300/05ed3fae3b45b2fcda6c80e76c4c8aed.png",
"size": "extralarge"
}
],
"@attr": {
"rank": "2"
}
}
],
"@attr": {
"tag": "Hip Hop",
"page": "1",
"perPage": "2",
"totalPages": "6491",
"total": "12982"
}
}我实现了以下Codable结构:
struct Root: Codable {
var albums: [Album]
}
struct Album: Codable {
var name: String
var mbid: String
var url: String
var image: AlbumImage
var artist: AlbumArtist
}
struct AlbumImage: Codable {
var text: String
var size: String
}
struct AlbumArtist: Codable {
var name: String
var mbid: String
var url: String
}然后,当我尝试使用以下函数解码JSON Data时:
func parse(json: Data) {
let decoder = JSONDecoder()
do {
let root = try decoder.decode(Root.self, from: json)
print("root", root.albums)
} catch {
print("Failed to decode:", error)
}
}调试器抛出以下错误:
Failed to decode: typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "albums", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
有人能帮我解决这个问题吗?我是错误地实现了Codable结构,还是错误地解析了它?谢谢。
发布于 2021-08-12 03:54:10
在这里,您遗漏了一个顶级属性,即"Albums“。根类有一个字典类型的属性"albums“,然后该类包含数组属性,如下所示:-
struct Root: Codable {
let albums: Albums
}
// MARK: - Albums
struct Albums: Codable {
let album: [Album]
let attr: AlbumsAttr
enum CodingKeys: String, CodingKey {
case album
case attr = "@attr"
}
}发布于 2021-08-12 05:55:56
正如我所看到的,您已经将图像类型指定为AlbumImage,但它期望的是AlbumImage而不是单个元素,请尝试更改模型的图像属性,如下所示
var镜像: AlbumImage
https://stackoverflow.com/questions/68749084
复制相似问题