gpt4 book ai didi

swift - Codable 用于使用单一模型映射不同的键值

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:45 25 4
gpt4 key购买 nike

JSON 1:

{    
"error_code" : 100,
"error_message" : "Something went wrong"
}

JSON 2

{
"failure_code" : 100,
"failure_message" : "Something not right here"
}

更改为以下代码以映射到 JSON 之上:

class Failure: Codable {
var code: Int?
var message: String?

private enum CodingKeys: String, CodingKey {
case code
case message
}
}

我们该怎么做?

最佳答案

这是您可以做到的一种方法:

import Cocoa
import Foundation

struct CustomError {
var code: Int
var message: String
}

extension CustomError : Decodable {
private enum FirstKeys: String, CodingKey {
case error_code, error_message
}
private enum SecondKeys: String, CodingKey {
case failure_code, failure_message
}

init(from decoder: Decoder) throws {
do {
print("Case 1")
let container = try decoder.container(keyedBy: FirstKeys.self)
code = try container.decode(Int.self, forKey: .error_code)
message = try container.decode(String.self, forKey: .error_message)
print("Error with code: \(code) and message: \(message)")
} catch {
print("Case 2")
let container = try decoder.container(keyedBy: SecondKeys.self)
code = try container.decode(Int.self, forKey: .failure_code)
message = try container.decode(String.self, forKey: .failure_message)
print("Error with code: \(code) and message: \(message)")
}
}
}

let json = """
{
"failure_code": 1,
"failure_message": "test"
}
""".data(using: .utf8)!
let error = try JSONDecoder().decode(CustomError.self, from: json)
print(error)

从我的 iPhone 发送

关于swift - Codable 用于使用单一模型映射不同的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54883601/

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