json - 如何解码包含数组 Swift 4 的 JSON 文件?
问题描述
我有一个我正在尝试解码的 JSON 文件,但收到一条错误消息:
typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "期望解码 Dictionary 但找到了一个数组。",底层错误: nil))
我的代码如下:
struct Phrase: Decodable {
let sentences: [String]
}
func getFromJSON() {
do {
let jsonURL = Bundle.main.url(forResource: "script", withExtension: "json")
let jsonDecoder = JSONDecoder()
let jsonData = try Data(contentsOf: jsonURL!)
let jsonSentence = try jsonDecoder.decode([Phrase].self, from: jsonData)
debugPrint(jsonSentence)
} catch {
print(error)
}
}
我一直在查看许多其他堆栈溢出问题,我注意到这些 JSON 文件的格式与我的不同。它们被格式化为字典,而我的是这样的-
[
["bin blue", "with A 2 soon"],
["set blue", "in A 9 soon"],
["lay blue", "at A 3 please"],
["3 5 zero zero 5 8"],
["place blue", "by A 6 now"],
["lay green", "at B ZERO now"],
["8 9 1 5 4 zero"]
]
我知道解码器正在寻找字典,但我如何让它解码数组呢?
解决方案
我想你需要
let jsonSentence = try jsonDecoder.decode([[String]].self, from: jsonData)
推荐阅读
- docusignapi - DocuSign,发送 2 个文档,signhere documentid 被忽略
- oracle - 如何在以下 SQL 查询中找到错误?
- api-platform.com - API 平台验证错误与 ORM 异常
- javascript - HTML中的背景不会根据可变数字而改变
- python - 无法使用列表满足 maxheap 属性
- azure - 如何在 Teams 中获取访问令牌?
- python - Pandas df:不同列中的组、bin和平均值?
- websocket - Nuxt Apollo websockets 链接选项?
- machine-learning - Scikit-learn 中的 R-Squared 和 explain_variance_score 有什么区别?
- javascript - 使用变量标识符反应更新嵌套对象的状态