简体   繁体   中英

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

The problem is that some parameters of the JSON are optional. You have to post your DeclarationInfoElement class to check.

Use something like this to detect the error.

   class DeclarationInfoElement: Decodable {
        let id: String?
        let created_date: String?
/// and so on
    }
@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")
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM