【问题标题】:Swift Codable Parsing keyNotFoundSwift 可编码解析 keyNotFound
【发布时间】:2020-09-09 13:53:18
【问题描述】:

我在进行编码时遇到了问题。任何帮助将不胜感激。我的操场上有以下内容

我的 JSON 文件

{
"metadata": {
  "generated": {
    "timestamp": 1549331723,
    "date": "2019-02-04 20:55:23"
  }
},
"data": {
    "CA": {
    "country-id": 25000,
    "country-iso": "CA",
    "country-eng": "Canada",
    "country-fra": "Canada"
    }
  }
}

我使用 quicktype 应用来帮助生成以下结构

// MARK: - Welcome
struct Welcome: Codable {
    let metadata: Metadata?
    let data: DataClass?
}

// MARK: - DataClass
struct DataClass: Codable {
    let ca: CA

    enum CodingKeys: String, CodingKey {
        case ca = "CA"
    }
}

// MARK: - CA
struct CA: Codable {
    let countryID: Int
    let countryISO, countryEng, countryFra: String

    enum CodingKeys: String, CodingKey {
        case countryID = "country-id"
        case countryISO = "country-iso"
        case countryEng = "country-eng"
        case countryFra = "country-fra"
    }
}

// MARK: - Metadata
struct Metadata: Codable {
    let generated: Generated?
}

// MARK: - Generated
struct Generated: Codable {
    let timestamp: Int?
    let date: String?
}

Swift 代码:

 do {
        guard let url = Bundle.main.url(forResource: "data", withExtension: "json") else { return 0 }

        let jsonData = try Data(contentsOf: url)
        let decoder = JSONDecoder()

        let data = try decoder.decode(CA.self, from: jsonData)
        print (data)
        print(data.countryID)
        print(data.countryISO)
    } catch { print("error" , error) }

这是我收到的错误消息。

jsonData 244 bytes
error keyNotFound(CodingKeys(stringValue: "country-id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"country-id\", intValue: nil) (\"country-id\").", underlyingError: nil))

值在那里,我不确定问题是什么。如果我从 json 和模型中删除 country-id,我会得到与 country-iso 相同的错误。

【问题讨论】:

  • let data = try decoder.decode(CA.self, from: jsonData) => let data = try decoder.decode(Welcome.self, from: jsonData).

标签: json swift codable


【解决方案1】:

那是因为你试图解码错误的类型。 CA 类型在您的 JSON 中嵌套了多个级别,您需要将根类型传递给 JSONDecoder.decode

let root = try decoder.decode(Welcome.self, from: jsonData)
guard let ca = root.data?.ca else { return 0 }
print(ca)

【讨论】:

  • 谢谢!说得通。我收到警告:表达式从“字符串?”隐式强制转换?到 'Any' 在这种情况下,Any 是什么?
  • @TheBear 检查我更新的答案。你需要处理dataOptional。您会收到该警告,因为您正在打印 Optional
  • 感谢 Dávid Pásztor。
  • @TheBear 很高兴我能帮上忙。如果您觉得我的回答有用,请考虑接受。如果您不确定如何操作,可以阅读What should I do when someone answers my question?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多