ios keyNotFound Swift Alamofire [duplicate]

7dl7o3gd  于 2023-05-02  发布在  iOS
关注(0)|答案(1)|浏览(130)

此问题已在此处有答案

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:无))”

2izufjch

2izufjch1#

API不发送“子类别”,可能“子类别”正在接收。你可以这样使用CodingKey

public struct ProductData : Codable {
    let id, category, subCategory, name, status: String
    
    enum CodingKeys: String, CodingKey {
        ...

        case subCategory        = "SubCategory"
        case category           = "Category"
        ...
    }

}

相关问题