JSONDecoder 找不到存在的密钥

JSONDecoder fails to find key that is present

当尝试解析来自 Github 的 REST api 中的 Create Team 调用的响应时,JSONDecoder 在解析许多蛇形键时失败存储库。通过JSONSerialization解码时,可以毫无问题地找到所有密钥。

例如Xcode11.0(11A420a)中Playground中运行时,用JSONDecoder解码时解码失败。

import Foundation

let jsonData = """
{
"id": 12345,
"name": "swift",
"ssh_url": "git@github.com:apple/swift.git"
}
""".data(using: .utf8)!

struct ExampleModel: Codable {
    let id: Int
    let name: String
    let sshURL: String
}

let jsonObject = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]
print("JSONSerialization:", jsonObject["id"]!, jsonObject["name"]!, jsonObject["ssh_url"]!)

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let decodedObject = try! decoder.decode(ExampleModel.self, from: jsonData) // Fails here
print("JSONDecoder:", decodedObject.id, decodedObject.name, decodedObject.sshURL)

// Output:
//
// JSONSerialization: 12345 swift git@github.com:apple/swift.git
// Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "sshURL", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"sshURL\", intValue: nil) (\"sshURL\"), converted to ssh_url.", underlyingError: nil)): file MyPlayground.playground, line 22

我应该做些什么来解析这个值?

Swift版本:

Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7)
Target: x86_64-apple-darwin19.0.0

尝试将 sshURL 更改为 sshUrlkeyDecodingStartegy 会将 sshURL 转换为 ssh_URL,这与您的密钥不匹配。 sshUrl 将转换为 ssh_url,这将匹配您的密钥。