我使用的是快速4 xcode 9.2,我在使用JSONDecoder时得到了下面的错误。
typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“期望解码数组,但找到了字典”,underlyingError: 0)
class Hits: Codable {
let hits: [Hit]
init(hits: [Hit]) {
self.hits = hits
}
}
class Hit: Codable {
let recipe: String
let uri: String
let label: String
let image: String
let source: String
let url: String
let shareAs: String
let yield: String
init(recipe: String, uri: String, label: String, image: String, source: String, url: String, shareAs: String, yield: String) {
self.recipe = recipe
self.uri = uri
self.label = label
self.image = image
self.source = source
self.url = url
self.shareAs = shareAs
self.yield = yield
}
}
func downloadJSON() {
guard let downloadURL = url else {return}
URLSession.shared.dataTask(with: downloadURL) { (data, urlResponse, error) in
guard let data = data, error == nil, urlResponse != nil else { print("Something is wrong"); return }
print("download completed")
do {
let decoder = JSONDecoder()
let foods = try decoder.decode([Hits].self, from: data)
print(foods)
} catch {
print(error)
}
}.resume()
}发布于 2019-12-07 15:17:59
错误清除表明您正在尝试解码数组,但实际类型是字典(单个对象)。
替换
let foods = try decoder.decode([Hits].self, from: data)使用
let foods = try decoder.decode(Hits.self, from: data)而且您的类(实际上结构是足够的)是
struct Recipe : Decodable {
let uri : URL
let label : String
let image : URL
let source : String
let url : URL
let shareAs : URL
let yield : Double
let calories, totalWeight, totalTime : Double
}
struct Hits: Decodable {
let hits: [Hit]
}
struct Hit: Decodable {
let recipe: Recipe
}发布于 2019-12-07 14:07:13
hits = try decoder.decode(Hits.self from: data)https://stackoverflow.com/questions/59226649
复制相似问题