jsonswiftalamofiredecodealamofire-request

Alamofire error to decode JSON response with Struct


I have a problem with my alamofire.request. The response is nil but I don't understand why.

My problem are: I use API of OpenFoodFacts, it works with a web address of this style: https://fr.openfoodfacts.org/api/v0/produit/3366321054229

I use Alamofire to get the request with a protocol, a session and a service.

My Protocol:

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

My Session:

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)
        }
    }
}

My service:

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)
            }
        }
    }
}

I have a file CheckerFridgeData contain Struct to decode the 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?
}

When I use my request to my code, I have no error but my responseJSON return nil

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

But if I print response.result.value as Any the code returns the JSON Value.

Have you any idea why I can't decode my struct with my JSON data ?

Thanks a lot for your help


Solution

  • I think the problem is about custom types. If you'd like to convert custom types you need to use CodingKeys protocol. When I looked your json there is no property like additivesTags there is additives_tags so you should use CodingKeys like following.

    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
        }
    }