【问题标题】:JSONDecoder fails to find key that is presentJSONDecoder 找不到存在的密钥
【发布时间】:2019-10-03 16:45:44
【问题描述】:

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

例如,在 Xcode 11.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

【问题讨论】:

标签: ios swift foundation jsondecoder


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-10-08
    • 2017-11-20
    • 1970-01-01
    • 2022-01-24
    • 2019-05-10
    • 2019-04-03
    • 2017-02-26
    • 2015-05-11
    • 1970-01-01
    相关资源
    最近更新 更多