簡體   English   中英

在Swift 4中解碼JSON時遇到問題

[英]Having trouble decoding JSON in Swift 4

這是響應JSON:

{
  "feed": {
    "title": "Top Albums",
    "id": "https://rss.itunes.apple.com/api/v1/us/apple-music/top-albums/all/25/explicit.json",
    "author": {
      "name": "iTunes Store",
      "uri": "http://wwww.apple.com/us/itunes/"
    },
    "links": [
      {
        "self": "https://rss.itunes.apple.com/api/v1/us/apple-music/top-albums/all/25/explicit.json"
      },
      {
        "alternate": "https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewTop?genreId=34&popId=82&app=music"
      }
    ],
    "copyright": "Copyright © 2018 Apple Inc. All rights reserved.",
    "country": "us",
    "icon": "http://itunes.apple.com/favicon.ico",
    "updated": "2018-07-17T01:41:38.000-07:00",
    "results": [
      {
        "artistName": "Drake",
        "id": "1405365674",
        "releaseDate": "2018-06-29",
        "name": "Scorpion",
        "kind": "album",
        "copyright": "℗ 2018 Young Money/Cash Money Records",
        "artistId": "271256",
        "artistUrl": "https://itunes.apple.com/us/artist/drake/271256?app=music",
        "artworkUrl100": "https://is4-ssl.mzstatic.com/image/thumb/Music125/v4/5d/9b/97/5d9b97d6-9f78-e43b-7ba7-c2c42f53a166/00602567879121.rgb.jpg/200x200bb.png",
        "genres": [
          {
            "genreId": "18",
            "name": "Hip-Hop/Rap",
            "url": "https://itunes.apple.com/us/genre/id18"
          },
          {
            "genreId": "34",
            "name": "Music",
            "url": "https://itunes.apple.com/us/genre/id34"
          }
        ],
        "url": "https://itunes.apple.com/us/album/scorpion/1405365674?app=music"
      },
      ...

這是我的代碼,嘗試對上述JSON進行解碼:

struct object: Decodable {
    struct feed: Decodable {
        let title: String?
        let id: Int?


        struct Author: Decodable {
            let name: String?
            let uri: String?
        }

        let author: Author?
        struct Link: Decodable {
            let url: String?
            private enum CodingKeys: String, CodingKey {
                case url = "self"
            }
        }
        let links: [Link]?
        let copyright: String?
        let country: String?
        let icon: String?
        let updated: String?

        let results: [Album]?
    }
}

struct Album: Decodable {
    let artistName: String?
    let id: Int?
    let releaseDate: String?
    let name: String?
    let artworkUrl100: String?
    let kind: String?
    let copyright: String?
    let artistId: Int?
    let artistUrl: String?
    struct Genre: Decodable {
        let genreId: Int?
        let name: String?
        let url: String?
    }
    let genres: [Genre]?
    let url: String?
}

我正在嘗試使用專輯名稱,藝術家名稱和圖像網址獲得結果。 我很難理解如何構建合適的結構以使用嵌套的json獲取數據。

當我嘗試在完成塊中獲取數據時,我最終得到的所有內容均為零。

//Networking
let jsonString = "https://rss.itunes.apple.com/api/v1/us/apple-music/top-albums/all/25/explicit.json"

guard let url = URL(string: jsonString) else { return }

URLSession.shared.dataTask(with: url) { (data, response, error) in

    guard let data = data else { return }

    do {
        let obj = try JSONDecoder().decode(object.feed.self, from: data)
        print(obj)
    } catch let jsonError {
        print("Error with json", jsonError)
    }

}.resume()

我的結果全是零:

feed(title: nil, id: nil, author: nil, links: nil, copyright: nil, country: nil, icon: nil, updated: nil, results: nil)

你有幾個問題。

首先,最外面的結構是密鑰feed下的對象

你需要:

struct object: Decodable {
    let feed: Feed
}

struct Feed: Decodable {
    let title: String
    let id: String

    let author: Author
    struct Link: Decodable {
        let url: String?
        private enum CodingKeys: String, CodingKey {
            case url = "self"
        }
    }
    let links: [Link]
    let copyright: String
    let country: String
    let icon: String
    let updated: String

    let results: [Album]
}

然后您可以通過以下方式對其進行解碼:

do {
    let obj = try JSONDecoder().decode(object.self, from: data)
    print(obj)
} catch let jsonError {
    print("Error with json", jsonError)
}    

請注意,所有“ id”都是String而不是Int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM