【问题标题】:Alamofire error to decode JSON response with Struct使用 Struct 解码 JSON 响应的 Alamofire 错误
【发布时间】:2019-11-04 06:07:43
【问题描述】:

我的 alamofire.request 有问题。响应为零,但我不明白为什么。

我的问题是:我使用 OpenFoodFacts 的 API,它适用于这种风格的网址:https://fr.openfoodfacts.org/api/v0/produit/3366321054229

我使用 Alamofire 通过协议、会话和服务获取请求。

我的协议:

protocol CheckerFridgeProtocol {
    func request(url: URL, parameters: Parameters, callback: @escaping (DataResponse<Any>) -> Void )
}

我的会话:

class CheckerFridgeSession: CheckerFridgeProtocol {

    func request(url: URL, parameters: Parameters, callback: @escaping (DataResponse<Any>) -> Void) {
        Alamofire.request(url, method: .get, parameters: parameters).responseJSON { responseData in
            callback(responseData)
        }
    }
}

我的服务:

class CheckerFridgeService {

    private var checkerFridgeSession: CheckerFridgeSession

    init(checkerFridgeSession: CheckerFridgeSession = CheckerFridgeSession()) {
        self.checkerFridgeSession = checkerFridgeSession
    }

    // get recipe ingredients
    func getRequest(barCode: String, callback: @escaping (Bool, CheckerFridgeData?) -> Void) {
        let parameters: Parameters = [:]

        let url = URL(string: "https://fr.openfoodfacts.org/api/v0/produit/\(barCode)")!

        checkerFridgeSession.request(url: url, parameters: parameters) { (response) in

            DispatchQueue.main.async {
                guard response.response?.statusCode == 200 else {
                    print("Response 400 Error")
                    callback(false, nil)
                    return
                }

                guard let data = response.data else {
                    print("Data error")
                    callback(false, nil)
                    return
                }

                guard let responseJSON = try? JSONDecoder().decode(CheckerFridgeData.self, from: data) else {
                    print("Response JSON Failed")
                    callback(false, nil)
                    return
                }

                guard responseJSON.status > 0 else {
                    print("Status Code 0")
                    callback(false, nil)
                    return
                }

                // print(response.result.value as Any)

                callback(true, responseJSON)
            }
        }
    }
}

我有一个文件 CheckerFridgeData 包含解码 responseJSON 的结构:

// MARK: - CheckerFridge
struct CheckerFridgeData: Codable {
    let status: Int
    let product: Product?
}

// MARK: - Product
struct Product: Codable {
    let additivesTags: [String]?
    let productNameFr: String?
    let imageSmallURL, imageFrontSmallURL: String?
}

当我对我的代码使用我的请求时,我没有错误,但我的 responseJSON 返回 nil

CheckerFridgeData(status: 1, product: Optional(Checker_Fridge.Product(additivesTags: nil, productNameFr: nil, imageSmallURL: nil, imageFrontSmallURL: nil)))

但如果我打印response.result.value as Any,代码将返回 JSON 值。

你知道为什么我不能用我的 JSON 数据解码我的结构吗?

非常感谢您的帮助

【问题讨论】:

    标签: json swift alamofire decode alamofire-request


    【解决方案1】:

    我认为问题在于自定义类型。如果您想转换自定义类型,您需要使用 CodingKeys 协议。当我查看您的 json 时,没有像 additivesTags 这样的属性有 additives_tags 所以您应该使用 CodingKeys,如下所示。

    struct Product: Codable {
        let additivesTags: [String]?
        let productNameFr: String?
        let imageSmallURL, imageFrontSmallURL: String?
    
        enum CodingKeys: String, CodingKey {
            case additivesTags = "additive_tags"
            case productNameFr = "product_name_fr"
            case imageSmallURL
        }
    }
    

    【讨论】:

    • 非常感谢@Atalay Asa,你是对的。这就是问题。祝你有美好的一天
    猜你喜欢
    • 2018-09-14
    • 2021-09-17
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2021-07-22
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多