首页 > 解决方案 > 为什么我在快速解析响应时出现错误

问题描述

我正在尝试调用 API,并且正在尝试将响应映射到模型类。但是每次,我都会收到一个无效数据的错误。

API调用如下。

 let endpoint = "http://apilayer.net/api/live?access_key=baab1114aeac6b4be74138cc3e6abe79&currencies=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]?
}

有人可以帮助我了解我哪里出错了吗?提前致谢。

标签: jsonswiftapiswift3

解决方案


错误消息有时会有所帮助。如果您发现错误并打印它,它会显示:

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "期望解码 Array 但找到了一个字典。",底层错误: nil))

Converted因此,实际上返回了一个对象时,需要一个数组。解决方案是更新期望以匹配实际响应:

let convertedValues = try decoder.decode(Converted.self, from: data)

推荐阅读