Alamofire错误,无法使用Struct

时间:2019-06-21 11:31:15

标签: json swift alamofire decode alamofire-request

我的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包含Struct来解码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数据解码结构吗?

非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我认为问题在于自定义类型。如果要转换自定义类型,则需要使用CodingKeys协议。当我查看您的json时,没有像 self.pivot = try JSONDecoder().decode([PivotProjectSum].self, from: data) let sum = self.pivot.map{ $0.counts }.reduce(0,+) print(sum) 这样的属性,所以没有additivesTags,所以您应该像下面那样使用CodingKeys。

additives_tags