简体   繁体   English

Swift Parse JSON 错误:没有与键 CodingKeys 关联的值(stringValue:\\"_source\\

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM