首页 > 解决方案 > 使用 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)

标签: swiftcodabledecodablejsondecoder

解决方案


推荐阅读