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

安全的JSON解码。仍然未找到获取密钥:没有与密钥关联的值';,json,swift,swift4,codable,Json,Swift,Swift4,Codable,IMGUR图像搜索返回json: {"data": [{ "title": "Family :)", "images": [{ "title": null, "description": null,

IMGUR图像搜索返回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():

在最后一行‘link=’上放置制动点时,我在其上着陆约48次。 据我所知,我们能够创建图像对象48次

但是,我收到一个错误,并且没有创建“响应”:

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

我还应该实施哪些“安全”解码实践?

该错误意味着您映射到
ImageData
的一个JSON对象缺少一个键
“images”
,但
ImageData
希望它在那里,因为它不是可选的

要修复此问题,需要将属性
图像
设置为可选:

struct ImageData: Codable {
   let title: String
   let images: [Image]? // <- here
}
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) ?? []
   }
}