[英]Swift Error: keyNotFound No value associated with key CodingKeys
[英]Swift Parse JSON Error : No value associated with key CodingKeys(stringValue: \"_source\
我正在嘗試解析以下 json 數據:
下面是我的結構:
struct Album: Decodable {
var source: [Sourcet]
enum CodingKeys: String, CodingKey {
case source = "_source"
}
}
struct Sourcet: Decodable {
var nome, endereco, uf, cidade, bairro: String
}
let response = try JSONDecoder().decode(Album.self, from: data)
我繼續收到錯誤:
keyNotFound(CodingKeys(stringValue: "_source", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \\"_source\\", intValue: nil) (\\ "_source\\").",underlyingError: nil))
這是由於 json 信息是一個數組嗎?我如何解析這些信息?
您的struct Album
是錯誤的,您正在解析Album.self
單個對象而不是數組。
試試下面的代碼:
struct Album: Decodable {
var source: Sourcet // change array to single object
enum CodingKeys: String, CodingKey {
case source = "_source"
}
}
struct Sourcet: Decodable {
var nome, uf : String
}
解析模型中的 json :
do {
let response = try JSONDecoder().decode([Album].self, from: data)
for item in response {
print(item.source.nome)
}
}catch{
print("Error: ",error)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.