swift - 使用 JSONDecoder 时出现 EXC_BAD_INSTRUCTION 错误
问题描述
我正在尝试使用 Swift 的 JSONDecoder 解码一个非常简单的 json,方法是使用KeyDecodingStrategy.convertFromSnakeCase
. 我收到以下错误,但我不明白为什么:
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
这是我得到的控制台输出:
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "latestBuildVersion", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"latestBuildVersion\", intValue: nil) (\"latestBuildVersion\"), converted to latest_build_version.", underlyingError: nil)): file MyPlayground.playground, line 14
当我不使用 keyDecodingStrategy 并使用编码键给出枚举时,一切正常。这是导致错误的操场代码:
import UIKit
struct App: Codable {
var stacks: Set<Stack>
}
struct Stack : Codable, Hashable {
var latestBuildVersion: Int
init(from decoder: Decoder) throws {
let container = try! decoder.container(keyedBy: Stack.CodingKeys.self)
latestBuildVersion = try! container.decode(Int.self, forKey: .latestBuildVersion)
}
}
let jsonData = """
{
"stacks":
[
{
"latest_build_version": 436346213
}
]
}
""".data(using: .utf8)!
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
let stack = try! jsonDecoder.decode(Stack.self, from: jsonData)
print(stack.latestBuildVersion)
解决方案
推荐阅读
- html - 如何在两个引导按钮之间留出空间
- sqlite - 参考数据更改列表视图中的按钮
- python - 单元测试 Python Azure 函数:如何使用 JSON 有效负载构造模拟测试请求消息?
- vim - 即使将列表项复制到局部变量,在快速修复项列表上调用排序时也会出错
- qt - 如何使用 Bazel 构建 Qt 项目?
- algorithm - 如何计算将 NXM 二进制矩阵转换为全 0 矩阵的成本,仅允许移动作为方阵切换?
- javascript - 通过 chrome.webRequest.onBeforeSendHeaders API 提取整个 http 请求
- html - Safari flex 内容上方的子水平滚动条(内容高度不正确)
- c# - 参考循环处理
- javascript - 导出excel文件中的对象数组(JavaScript)