json - 安全 JSON 解码。仍然收到 Key not found : No value associated with key'

标签 json swift swift4 codable

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

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

当在最后一行“link =”上放置制动点时,我在上面着陆了大约 48 次。 据我了解,我们能够创建 Image 对象 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 需要它在那里,因为它不是可选的。

要修复此问题,您需要将属性 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) ?? []
   }
}

关于json - 安全 JSON 解码。仍然收到 Key not found : No value associated with key',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66308404/

相关文章:

javascript - 如何获取从 Node js(express js 中间件)作为 json 响应发送的 Angular js 中的数据

javascript - Atom编辑器,atom-beautify插件错误: Uncaught TypeError: Cannot read property 'setScrollTop' of null

swift - 根据特定参数对单词词典进行排序

ios - 使用我的 Vimeo 帐户中的视频填充 UITableView

ios - 如何改变 "scrollView.setContentOffset"的速度

javascript - Django DRF 从 POST 读取 json?

json - 无法使用 SwiftyJSON 访问 JSON

ios - 如何快速从我的 map View 上的特定点获取经度和纬度?

ios - 在 swift 4.0 中查找 realm 的 schemaVersion

ios - UIBezierPath 未正确渲染