簡體   English   中英

使用帶(無)鍵的字典解碼 JSON

[英]Decoding JSON with a dictionary with (no) keys

我無法使用結構解碼簡單的 JSON api 結果。

這是 JSON 結構(部分):

{
  "ad": "Andorra",
  "ae": "United Arab Emirates",
  "af": "Afghanistan",
  "ag": "Antigua and Barbuda",
  "ai": "Anguilla",
  "al": "Albania"
}

這是我創建的結構:

struct Countries: Codable {
    var countries: [Country]
}

struct Country: Codable, Identifiable {
    var id = UUID()
    var code: String
    var name: String
}

並使用 API 我這樣做是為了嘗試對其進行解碼:

let decodedResponse = try JSONDecoder().decode(Countries.self, from: data)

目前這是錯誤:

No value associated with key CodingKeys(stringValue: "countries", intValue: nil) ("countries").

據我了解, JSON 結果有兩件事,鍵和值。 在這種情況下,鍵是國家代碼(兩個字母),值是國家名稱。 我確實想在我的應用程序中同時使用它們,但我很難使用結構來同時使用鍵和值。 目前的錯誤也是因為字典本身沒有鍵。 但我也可以想象一個國家的價值觀也行不通。

實現自定義encoderdecoder邏輯可以幫助在預期的Countries [String:String]和 Country / [Country]之間進行轉換。

struct Countries: Codable {
  struct Country {
    let code: String
    let name: String
  }
  
  let countries: [Country]

  //custom decoder logic; from json to model
  init(from decoder: Decoder) throws {
    let container = try decoder.singleValueContainer()
    
    let dict = try container.decode([String:String].self)
    countries = dict.map(Country.init)
  }

  //custom encoder logic; from model to json
  func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()

    var dict = [String:String]()
    countries.forEach { (country) in
      dict[country.code] = country.name
    }
    try container.encode(dict)
  }
}

使用示例**:

let jsonData = """
{
  "ad": "Andorra",
  "ae": "United Arab Emirates",
  "af": "Afghanistan",
  "ag": "Antigua and Barbuda",
  "ai": "Anguilla",
  "al": "Albania"
}
""".data(using: .utf8)!

do {
  let result = try JSONDecoder().decode(Countries.self, from: jsonData)
  result.countries.forEach { print($0) }
  
  let data = try JSONEncoder().encode(result)
  let json = String(data: data, encoding: .utf8)!
  print(json)
} catch {
  print(error)
}

**忽略強制解包,它只是測試代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM