[英]Swift Parse JSON Error : No value associated with key CodingKeys(stringValue: \"_source\
I am attempting to parse the following json data:我正在尝试解析以下 json 数据:
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))
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?这是由于 json 信息是一个数组吗?我如何解析这些信息?
Your struct Album
is wrong and you're parsing Album.self
single object instead of array.您的
struct Album
是错误的,您正在解析Album.self
单个对象而不是数组。
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 :解析模型中的 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.