I am attempting to parse the following json data:
Below is my struct:
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)
I continue getting the error:
keyNotFound(CodingKeys(stringValue: "_source", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \\"_source\\", intValue: nil) (\\"_source\\").", underlyingError: nil))
Is this due to the json information being an array?.How would I be able to parse this information?
Your struct Album
is wrong and you're parsing Album.self
single object instead of array.
Try below code :
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
}
To parse json in model :
do {
let response = try JSONDecoder().decode([Album].self, from: data)
for item in response {
print(item.source.nome)
}
}catch{
print("Error: ",error)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.