我正在尝试解码嵌套的JSON。问题是顶层和嵌套键的名称相似。喜欢:
{
success: bool
message: String
error: {
message: String
}
}
从后端,我将收到成功消息或失败消息。如果成功为 true,则不会返回错误键,如果为 false,则发送错误和消息。
因此,如果成功:
{
success: true
message: "Success message"
}
如果失败:
{
success: false
error:{
message: "Failed message"
}
}
以上将是返回的 json。这是我的解码结构:
struct loginResponse : Codable{
var success: Bool
var success_message: String
var error_message: String
enum loginResponseKeys: String, CodingKey{
case success
case error
case success_message = "message" // raw value is not unique
case error_message = "message"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: loginResponseKeys.self)
let error = try container.nestedContainer(keyedBy: loginResponseKeys.self, forKey: .error)
error_message = try error.decode(String.self, forKey: .error_message)
let message = try container.decode(String.self, forKey:.success_message)
}
没错,它说原始值不是唯一的。但是我该如何克服呢?
你可以为错误消息创建结构
struct LoginResponse: Codable {
let success: Bool
let message: String?
let error: ErrorMessage?
}
struct ErrorMessage: Codable {
let message: String?
}
extension LoginResponse {
init(data: Data) throws {
self = try JSONDecoder().decode(LoginResponse.self, from: data)
}
}
假设这个 Json:
{
"success": true,
"message": "success",
"error": {
"message": "Error Message"
}
}
你只需要创建一个嵌套的ErrorResponse
结构。将message
和error
设置为可选,并且仅根据success
的值解码其中一个。
您还应该符合 Swift 命名约定,即类型名称为 UpperCamelCase,变量名称为 lowerCamelCase。
struct LoginResponse : Codable{
let success: Bool
var successMessage: String?
var error: ErrorResponse?
struct ErrorResponse: Codable {
let message: String
}
enum LoginResponseKeys: String, CodingKey{
case success, error, successMessage = "message"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: LoginResponseKeys.self)
success = try container.decode(Bool.self, forKey: .success)
if success {
successMessage = try container.decode(String.self, forKey: .successMessage)
} else {
error = try container.decode(ErrorResponse.self, forKey: .error)
}
}
}
使用 KeyedCodable 可能是,请注意,您将拥有单个"消息"属性,该属性将包含成功或失败的消息,具体取决于"成功"值:
struct LoginResponse: Codable, Keyedable {
private(set) var success: Bool!
private(set) var message: String!
mutating func map(map: KeyMap) throws {
try success <-> map["success"]
let messageKey = success ? "message" : "error.message"
try message <-> map[messageKey]
}
init(from decoder: Decoder) throws {
try KeyedDecoder(with: decoder).decode(to: &self)
}
}