解析 Swift 中嵌套的 JSON 5

parsing nested JSON in Swift 5

无法弄清楚如何为这个嵌套 JSON 构建结构。我很接近但错过了一些东西..

我正在尝试验证我是否正确加载...前两个工作很好,嵌套数据失败

print(json.pagination.items) // this works
print(json.releases[3].date_added) // this works 
print(json.releases[3].basicInformation?.year) //NOT WORKING, returns nil

这是内置的结构

struct Response: Codable {
    let pagination: MyResult
    let releases: [MyReleases]
}

struct MyResult: Codable {
    var page: Int
    var per_page: Int
    var items: Int
}

struct MyReleases: Codable {
    var date_added: String
    let basicInformation: BasicInformation?
}

struct BasicInformation: Codable {
    let title: String
    let year: Int

    enum CodingKeys: String, CodingKey {
        case title, year
    }
}

我的JSON是

{
   "pagination":{
      "page":1,
      "pages":2,
      "per_page":50,
      "items":81,
      "urls":{
         "last":"https://api.discogs.com/users/douglasbrown/collection/folders/0/releases?page=2&per_page=50",
         "next":"https://api.discogs.com/users/douglasbrown/collection/folders/0/releases?page=2&per_page=50"
      }
   },
   "releases":[
      {
         "id":9393649,
         "instance_id":656332897,
         "date_added":"2021-03-28T10:54:09-07:00",
         "rating":2,
         "basic_information":{
            "id":9393649,
            "master_id":353625,
            "master_url":"https://api.discogs.com/masters/353625",
            "resource_url":"https://api.discogs.com/releases/9393649",
            "thumb":"",
            "cover_image":"",
            "title":"Ten Summoner's Tales",
            "year":2016
         }
     }
     ]
}

如有任何帮助,我们将不胜感激。我很接近但错过了一些东西...... :(

首先

json.releases[3].date_added

不适用于给定的 JSON,它会崩溃,因为只有一个 release


MyReleases 中,您必须添加 CodingKeys 以映射 snake_case 名称

struct MyReleases: Codable {
    var dateAdded: String
    let basicInformation: BasicInformation?

    private enum CodingKeys: String, CodingKey {
        case basicInformation = "basic_information", dateAdded = "date_added"
    }
}

或添加.convertFromSnakeCase密钥解码策略。

您甚至可以使用 .iso8601 日期解码策略将 dateAdded 解码为 Date