I am trying to decode a nested JSON. The problem is that the top level and a nested keys' names are similar. Like:
{
success: bool
message: String
error: {
message: String
}
}
From the back end I would be receiving a success message or a failed message. If the success is true, the error key would not be returned back and if it is false, then the error along with the message is sent.
so if it is successful:
{
success: true
message: "Success message"
}
If it fails:
{
success: false
error:{
message: "Failed message"
}
}
The above will be the returned json. This is my struct for decoding:
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)
}
Rightly so, it says that the raw value is not unique. But how do I overcome that?