ios - 使用 Alamofire 解码 json 时出错

标签 ios json swift alamofire

我尝试使用 Alamofire 从网络解码 JSON 数据。我的应用程序发送相同的 GET 请求,但 id 有所不同。有些 JSON 解码成功,但有些无法解码。可能是什么问题?我该如何解决这个问题?所有响应均由 JSON 验证器检查且有效。尝试使用 URLSession.shared.dataTask(with: url) 进行解码无法解码单个响应,即使是使用 Alamofire 成功解码的响应

代码是:

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

控制台输出为:

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

最佳答案

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

关于ios - 使用 Alamofire 解码 json 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51837571/

相关文章:

ios - iOS App Containing Extension 和 Extension (not Host App) 之间如何通信

ios - UIView动画增加内存

javascript - Lodash key与数组具有相同的属性

swift - 如何在 Swift 中编写 initwithcoder?

ios - 以编程方式访问 Xcode 颜色选择器 'Pencils' 选项

iphone - 如何在 Cocoa Touch 中处理用户名?

ios - 在react-native ios构建中找不到应用程序图标

java - 在android中使用List<NameValuePair>创建一个json字符串

javascript - jQuery each() 在 null 上中断

ios - Xcode( swift ): Changing UIButton attributes in a different UIViewController class than that in which they were referenced