此问题已在此处有答案:
Error: keyNotFound(CodingKeys(stringValue: "origin", intValue: nil),(1个答案)
3天前关闭。
模型类
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调用返回的错误语句
“keyNotFound(CodingKeys(stringValue:“subCategory”,intValue:nil),Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“data”,intValue:nil),_JSONKey(stringValue:“索引0”,intValue:0)],debugDescription:“没有与键CodingKeys(stringValue:“subCategory”,intValue:nil)(“subCategory”)。“,underlyingError:无))”
1条答案
按热度按时间2izufjch1#
API不发送“子类别”,可能“子类别”正在接收。你可以这样使用CodingKey