Search code examples
iosjsonswiftalamofire

errors decoding json with Alamofire


I try to decode JSON data from web using Alamofire. My app is sending the same GET requests, which differs by id. Some JSON is decoded successfully, but some can not be decoded. What can be the problem? How can I solve this issue? All responses are checked by JSON validator and are valid. Trying to decode with URLSession.shared.dataTask(with: url) just cannot decode a single response, even response that was successfully decoded with Alamofire

Code is:

var hostURL = "https://public-api.nazk.gov.ua/v1/declaration/"
    hostURL = hostURL + declarationID
    print(hostURL)

    Alamofire.request(hostURL).responseData { response in
        switch response.result {
        case .success(let data):
            let declarationInfoElement = try? JSONDecoder().decode(DeclarationInfoElement.self, from: data)
            print(declarationInfoElement)
        case .failure:
            print("fail")
        }
    }

Console output is:

https://public-api.nazk.gov.ua/v1/declaration/3509369f-b751-444a-be38-dfa66bb8728f
https://public-api.nazk.gov.ua/v1/declaration/3e7ad106-2053-48e4-a5d2-a65a9af313be
https://public-api.nazk.gov.ua/v1/declaration/743b61d5-5082-409f-baa0-9742b4cc2751
https://public-api.nazk.gov.ua/v1/declaration/5d98b3d9-8ca6-4d5d-b39f-e4de98d451aa
https://public-api.nazk.gov.ua/v1/declaration/7e3c488c-4d6a-49a3-aefb-c760f317dca4


nil
Optional(Customs_UA.DeclarationInfoElement(id: "4647cd5d-5877-4606-8e61-5ac5869b71e0")
nil
nil
nil

Solution

  • @objc func getJSON(){
        let hostURL = "https://public-api.nazk.gov.ua/v1/declaration/"
    
        print(hostURL)
    
        Alamofire.request(hostURL).responseData { response in
            switch response.result {
            case .success(let data):
    
                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
                    {
    
                        print(json)
    
                    } else {
                        print("bad json")
                    }
                } catch let error as NSError {
                    print(error)
                }
    
                print(data)
            case .failure:
                print("fail")
            }
        }
    }