使用Alamofire解析API响应时出现DecodingError解码错误如何解决
错误根因
你定义的identityVerification属性类型为[cst_IdentityVerification]?,数组的元素是非可选的cst_IdentityVerification类型,但接口返回的identity_verifications数组里包含null值,Codable无法将null解析为非可选的自定义结构体,因此触发解码失败。
修复方案
下面提供两种常用修复方案,可根据业务需求选择:
方案1:修改数组元素为可选类型
直接允许数组内存在nil值,修改代码成本最低:
- 修改
cst_Value里的属性定义:
// 原代码 // let identityVerification : [cst_IdentityVerification]? // 修改后 let identityVerification : [cst_IdentityVerification?]?
- 修改
cst_Value自定义解码逻辑中对应行的解码类型:
// 原代码 // identityVerification = try values.decodeIfPresent([cst_IdentityVerification].self, forKey: .identityVerification) // 修改后 identityVerification = try values.decodeIfPresent([cst_IdentityVerification?].self, forKey: .identityVerification)
注意:后续使用该数组时需要对每个元素单独解包,处理nil的情况。
方案2:解码时自动过滤null值(更推荐)
自定义解码逻辑,自动跳过数组中的null/解码失败的元素,最终得到的数组只包含有效对象,使用更方便:
- 先定义一个空的
Null结构体,用于占位解析null值:
struct Null: Codable {}
- 替换
cst_Value的init方法中解析identityVerification的逻辑:
// 删掉原来的identityVerification解码代码,替换为下面的逻辑 if var unkeyedContainer = try? values.nestedUnkeyedContainer(forKey: .identityVerification) { var validElements = [cst_IdentityVerification]() while !unkeyedContainer.isAtEnd { if let element = try? unkeyedContainer.decode(cst_IdentityVerification.self) { validElements.append(element) } else { // 跳过null值 _ = try? unkeyedContainer.decode(Null.self) } } identityVerification = validElements } else { identityVerification = nil }
额外注意事项
当前接口返回的JSON中还有customer_status、customer_status_description、wallet_status等字段,如果你需要使用这些字段,记得在cst_Value中补充对应属性和CodingKeys映射,不需要的话可以忽略,不会影响解码。
内容的提问来源于stack exchange,提问作者Mohammad Othman
相关产品推荐
相关产品推荐

