Swift Alamofire解析JSON遇keyNotFound(subCategory)错误求助
解决Swift Alamofire JSON解码keyNotFound错误
问题说明
使用Swift的Alamofire框架调用API时,出现JSON解码错误,具体错误信息如下:
keyNotFound(CodingKeys(stringValue: "subCategory", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "subCategory", intValue: nil) ("subCategory").", underlyingError: nil))
相关代码
Model类代码
public struct Products : Codable { let data: [ProductData] let error: Bool let message: String } public struct ProductData : Codable { let id, category, subCategory, name, status: String }
ViewModel类代码
import Foundation import Alamofire final class GetProductsViewModel : ObservableObject { @Published var products : [ProductData] = [] func productRequest() { let productsurl = "https://auroraa.site/suresh-packers/admin/api/get-products.php" AF.request(productsurl, method: .post, parameters: ["type": "get_products","sub_category": "2"], encoding: URLEncoding.default, headers: nil, interceptor: nil).response { responce in switch responce.result { case .success(let data): do { let jsonData = try JSONDecoder().decode(Products.self, from: data!) print("Product Names : ",jsonData) self.products = jsonData.data } catch { print(error) } case .failure(let error): print(error) } } } }
解决方法
这个错误的核心原因是:API返回的JSON数据中,至少有一个data数组内的对象不包含subCategory字段。以下是两种可行的解决思路:
1. 将subCategory设为可选类型
如果API允许部分条目缺失subCategory字段,直接修改模型属性为可选字符串即可:
public struct ProductData : Codable { let id, category, name, status: String let subCategory: String? // 改为可选类型 }
2. 给subCategory设置默认值
如果希望即使字段不存在,也能有一个默认值(比如空字符串),可以自定义解码初始化方法:
public struct ProductData : Codable { let id, category, subCategory, name, status: String public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) category = try container.decode(String.self, forKey: .category) // 字段不存在时用空字符串作为默认值 subCategory = try container.decodeIfPresent(String.self, forKey: .subCategory) ?? "" name = try container.decode(String.self, forKey: .name) status = try container.decode(String.self, forKey: .status) } }
额外排查建议
- 可以先打印API返回的原始数据,确认具体哪些条目缺少
subCategory字段:
在.success分支中添加以下代码:if let jsonString = String(data: data!, encoding: .utf8) { print("API返回原始数据:", jsonString) } - 如果是API接口的问题,也可以联系后端调整,确保所有
data条目都包含subCategory字段。
内容的提问来源于stack exchange,提问作者SasidharanIOS
相关产品推荐
相关产品推荐

