当试图在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发布于 2019-10-04 00:53:04
尝试将sshURL更改为sshUrl。keyDecodingStartegy会将sshURL转换为与您的密钥不匹配的ssh_URL。sshUrl将被转换为与您的密钥匹配的ssh_url。
https://stackoverflow.com/questions/58223590
复制相似问题