Swift解码顶层JSON数组时访问title字段报错如何解决
问题描述
对接口返回的顶层数组结构JSON做Codable解码时,尝试提取数组内元素的title字段触发解码错误。已知接口返回无外层包裹键,数组内对象仅包含title/url/source三个字段。
原有问题代码
模型定义
struct SpaceNewsModel: Identifiable, Codable { var id = UUID() let title: String let url: String let source: String }
网络请求解码逻辑
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in if error != nil { print(error!) } else { let decoder = JSONDecoder() if let safeData = data { do { let astroNews = try decoder.decode([SpaceNewsModel].self, from: safeData) print(astroNews[0].title) } catch { print("DEBUG: Error getting news articles \(error.localizedDescription)") } } let httpResponse = response as? HTTPURLResponse } }) task.resume()
接口返回JSON示例
[ { "title": "Wales' new £2bn space strategy hopes", "url": "https://www.bbc.co.uk/news/uk-wales-60433763", "source": "bbc" }, { "title": "Could Port Talbot become a centre of space tech? Video, 00:02:02Could Port Talbot become a centre of space tech?", "url": "https://www.bbc.co.uk/news/uk-wales-60471170", "source": "bbc" } ]
报错根因
decode([SpaceNewsModel].self, from: safeData) 解码顶层数组的写法完全正确,报错与JSON是否为顶层数组结构无关。
核心触发逻辑:即使为id属性设置了默认值UUID(),系统自动合成的Codable解码实现默认仍会尝试从JSON中匹配id对应的键,而接口返回的JSON对象不包含id字段,最终触发keyNotFound解码错误。该逻辑也匹配观测到的现象:无存储属性的空结构体解码无异常,一旦添加需要匹配JSON键的存储属性就会解码失败。
修复方案
给SpaceNewsModel显式声明CodingKeys枚举,把id排除在需要从JSON解码的字段列表外即可,修改后的模型代码如下:
struct SpaceNewsModel: Identifiable, Codable { var id = UUID() let title: String let url: String let source: String // 仅列出需要从JSON解析的字段,id会自动使用预设默认值 enum CodingKeys: String, CodingKey { case title, url, source } }
修改后原有解码逻辑无需调整,解码成功后即可正常通过astroNews[0].title访问对应字段值。
内容的提问来源于stack exchange,提问作者Tomas
相关产品推荐
相关产品推荐

