Reputation: 29
I couldn't find anything about this due to the amount of people that confuse array for a dictionary, but for my case its about the JSON response being a dictionary when there is only one property otherwise it will be an array. So how would i go about this?
....
struct MessageContainer: Codable {
var message: MessageDetail // This will be an array if there is more than one result.
enum CodingKeys: String, CodingKey {
case message = "Message"
}
}
....
Examples of Dictionary and Array response
Upvotes: 0
Views: 265
Reputation: 17874
You can implement a custom init
method that converts a "single" MessageDetail
into a one-element array:
struct MessageContainer: Codable {
let message: [MessageDetail]
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let message = try? container.decode(MessageDetail.self, forKey: .message) {
self.message = [message]
} else {
self.message = try container.decode([MessageDetail].self, forKey: .message)
}
}
}
Upvotes: 3