gpt4 book ai didi

ios - JSONDecoder 找不到存在的 key

转载 作者:行者123 更新时间:2023-11-28 10:27:22 25 4
gpt4 key购买 nike

尝试解析来自 Create Team 的响应时调用 Github 的 REST api,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

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

快速版本:

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,这与您的 key 不匹配。 sshUrl 将转换为 ssh_url,它将与您的 key 匹配。

关于ios - JSONDecoder 找不到存在的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58223590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com