首页 > 解决方案 > 为什么某些变量为零?

问题描述

我正在尝试解码此 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,尽管大多数其他变量似乎没问题

标签: jsonswiftdecoding

解决方案


添加 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结构中也有错误,请更改imagesimage(或使用 CodingKey 映射到那里)。有关解码 json 的更多信息,请参阅Apple 的文档


推荐阅读