json - How to decode this JSON with the new decodable protocol?
问题描述
Problem
I tried to decode my JSON file so it will be casted to native struct types. Apparently it does not work and I have no idea why. I replicated all the JSON objects in structs so the decodable protocol can do its work.
The JSON File
The JSON file can be found here: https://pastebin.com/hZxmDMue
The models (structs)
These are the models that reflect the exact same objects in the JSON file.
struct Appstructure: Decodable {
var data: [Subdata]
}
struct Subdata: Decodable {
var favourites: Items
var cart: Items
}
struct Items: Decodable {
var items: [Item]
}
struct Item: Decodable {
var type: String
var content: Content
}
struct Content: Decodable {
var productLines: [String]
var productImage: String
}
The JSON Parsing
I am using the provided JSONDecoder by apple like so:
func fetchAppStructure() -> Appstructure? {
guard let path = Bundle.main.path(forResource: "iMessage-test-version-3", ofType: "json") else { return nil }
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: []) else { return nil }
do {
try JSONDecoder().decode(Appstructure.self, from: data)
} catch {
print(error.localizedDescription)
}
return nil
}
Error
However I receive the following decoding error.
DecodingError
▿ keyNotFound : 2 elements
- .0 : CodingKeys(stringValue: "cart", intValue: nil)
▿ .1 : Context
▿ codingPath : 2 elements
- 0 : CodingKeys(stringValue: "data", intValue: nil)
▿ 1 : _JSONKey(stringValue: "Index 0", intValue: 0)
- stringValue : "Index 0"
▿ intValue : Optional<Int>
- some : 0
- debugDescription : "No value associated with key CodingKeys(stringValue: \"cart\", intValue: nil) (\"cart\")."
- underlyingError : nil
If anything else is needed to reproduce this bug please ask. It is probably something small in logical thinking. Hopefully somebody sees the issue! Thanks in advance.
解决方案
推荐阅读
- javascript - 在 Reactjs 中,我如何为复选框做自定义消息。我看到这个问题有很多答案适用于javascript而不是reactjs
- java - 在底部导航抽屉中加载带有标记列表的地图片段
- python - Pandas - 添加交替值的列
- ruby-on-rails - rails 5 API 低级缓存
- java - 如何将小黄瓜步骤定义数据映射到 Cucumber 中的 Java 对象?
- java - 类对象关系如何工作?
- google-apps-script - ScriptProperties 和 UserProperties 已被弃用
- python - 用例如 UTF-8 编码的文本文件中的字典替换单词
- python - AccessToken 匹配查询不存在。使用 Postman 匹配查询不存在
- r - 如何使用 caret 包解释模型输出的准确性