简体   繁体   English

在Swift 4中解码JSON时遇到问题

[英]Having trouble decoding JSON in Swift 4

Here is the response JSON: 这是响应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"
      },
      ...

And this is my code attempting to decode the above JSON: 这是我的代码,尝试对上述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?
}

I am attempting to obtain the results with album name, artist name and image url. 我正在尝试使用专辑名称,艺术家名称和图像网址获得结果。 I am having difficulty understanding how to construct a suitable structure to obtain the data with a nested json. 我很难理解如何构建合适的结构以使用嵌套的json获取数据。

When I attempt to obtain the data within my completion block, i just end up getting nil values for everything. 当我尝试在完成块中获取数据时,我最终得到的所有内容均为零。

//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()

And my result is all nil: 我的结果全是零:

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

You have a few issues. 你有几个问题。

Firstly, the outermost structure is an object under the key feed 首先,最外面的结构是密钥feed下的对象

You need: 你需要:

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]
}

and then you would decode it via: 然后您可以通过以下方式对其进行解码:

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

Note that all of the "ids" are String s not Int s 请注意,所有“ id”都是String而不是Int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM