安全 JSON 解码。仍然找不到密钥:没有与密钥关联的值'

Safe JSON Decoding. Still getting Key not found: No value associated with key'

IMGUR 图片搜索 returns json:

    {"data": [{
                "title": "Family :)",
               "images": [{
                    "title": null,
                    "description": null,
                    "nsfw": null,
                    "link": "https:\/\/i.imgur.com\/oe5BrCu.jpg",
            }]
        } ]
    }

模型对象已配置:

struct ImgurResponse: Codable {
    let data: [ImageData]
}

struct ImageData: Codable {
    let title: String
    let images: [Image]
}

struct Image: Codable {
    let title, description, nsfw: String
    let link: String
    
    enum CodingKeys: String, CodingKey {
        case title
        case description
        case nsfw
        case link
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        title = try container.decodeIfPresent(String.self, forKey: .title) ?? ""
        description = try container.decodeIfPresent(String.self, forKey: .description) ?? ""
        nsfw = try container.decodeIfPresent(String.self, forKey: .nsfw) ?? ""
        link = try container.decodeIfPresent(String.self, forKey: .link) ?? ""
    }

调用 JSONDecoder():

let response = try JSONDecoder().decode(ImgurResponse.self, from: data)          

在最后一行设置刹车点时'link = '我在上面降落了大约 48 次。 据我了解,我们能够创建 Image 对象 48 次。

但是,我遇到了一个错误,'response' 没有创建:

Key 'CodingKeys(stringValue: "images", intValue: nil)' not found: No value associated with key CodingKeys(stringValue: "images", intValue: nil) ("images").
codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 49", intValue: 49)]

我还应该实施哪些 'safe' 解码实践?

错误意味着您映射到 ImageData 的 JSON 对象之一缺少键 "images",但 ImageData 期望它在那里,因为这不是可选的。

要修复,您需要将 属性 images 设为可选:

struct ImageData: Codable {
   let title: String
   let images: [Image]? // <- here
}

通常,可选数组很难使用,因此您可能需要考虑在缺少键时创建一个空数组:

struct ImageData {
   let title: String
   let images: [Image]
}

extension ImageData: Codable {
   init(from decoder: Decoder) throws {
      let container = try decoder.container(keyedBy: CodingKeys.self)
        
      title = try container.decode(String.self, forKey: .title)
      images = try container.decodeIfPresent([Image].self, forKey: .images) ?? []
   }
}