我尝试使用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
答案 0 :(得分:0)
问题是JSON的某些参数是可选的。您必须发布您的DeclarationInfoElement类进行检查。
使用类似的方法来检测错误。
class DeclarationInfoElement: Decodable {
let id: String?
let created_date: String?
/// and so on
}
答案 1 :(得分:0)
@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")
}
}
}