Swift Codable解析keyNotFound

编程入门 行业动态 更新时间:2024-10-05 15:31:11
本文介绍了Swift Codable解析keyNotFound的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在编码方面遇到了问题。任何帮助将不胜感激。我在操场上有以下东西

I'm having an issue getting codable going. Any help would greatly appreciated. I have the following in my playground

我的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应用程序来帮助生成以下内容

I used the quicktype app to help generate the following structs

// 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? }

快速代码:

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) }

这是我收到的错误消息。

This is the error message I get.

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也会收到相同的错误。

The value is there, I'm not sure what the issue is. If I take remove country-id from the json and model, I get the same error for country-iso.

推荐答案

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

That's because you are trying to decode the wrong type. The CA type is nested several levels in your JSON, you need to pass the root type to JSONDecoder.decode.

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

更多推荐

Swift Codable解析keyNotFound

本文发布于:2023-11-26 23:26:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Swift   Codable   keyNotFound

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!