json - 为什么我在快速解析响应时出现错误
问题描述
我正在尝试调用 API,并且正在尝试将响应映射到模型类。但是每次,我都会收到一个无效数据的错误。
API调用如下。
let endpoint = "http://apilayer.net/api/live?access_key=baab1114aeac6b4be74138cc3e6abe79¤cies=EUR,GBP,CAD,PLN,INR&source=USD&format=1"
guard let url = URL(string: endpoint) else {
completed(.failure(.invalidEndPoint))
return
}
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let _ = error {
completed(.failure(.unableToComplete))
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
completed(.failure(.invalidResponse))
return
}
guard let data = data else {
completed(.failure(.invalidData))
return
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let convertedValues = try decoder.decode([Converted].self, from: data)
completed(.success(convertedValues))
} catch {
completed(.failure(.invalidData))
}
}
task.resume()
}
示例响应如下。
{
"success":true,
"terms":"https:\/\/currencylayer.com\/terms",
"privacy":"https:\/\/currencylayer.com\/privacy",
"timestamp":1610986207,
"source":"USD",
"quotes":{
"USDEUR":0.828185,
"USDGBP":0.736595,
"USDCAD":1.276345,
"USDPLN":3.75205
}
}
模型类
struct Converted: Codable {
let success: Bool
let terms, privacy: String?
let timestamp: Int?
let source: String?
let quotes: [String: Double]?
}
有人可以帮助我了解我哪里出错了吗?提前致谢。
解决方案
错误消息有时会有所帮助。如果您发现错误并打印它,它会显示:
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "期望解码 Array 但找到了一个字典。",底层错误: nil))
Converted
因此,实际上返回了一个对象时,需要一个数组。解决方案是更新期望以匹配实际响应:
let convertedValues = try decoder.decode(Converted.self, from: data)
推荐阅读
- javascript - 为什么我的变量在模板中未定义?
- typescript - Typescript React Native Maps Polyline 跟踪路线(如优步)
- python - Python + Selenium:Chrome 驱动程序无法写入 cookie 文件夹
- python - 无论python版本如何,conda都拒绝安装
- c# - 为什么选择这种通用方法而不是更好的匹配?
- c# - c#中如何比较一维数组和二维数组
- kotlin - Mockito 如何验证分配?
- python - 试图创建一个类来减少重复代码,但由于缺乏更好的术语而陷入枚举问题
- mysql - 每次我选择它时,MySQL 函数的执行时间都会增加
- excel - 如何在 MS-Excel 中连续复制多个单元格?