27Nights
27Nights

Reputation: 29

How is my Codable struct supposed to look like if the JSON response returns a dictionary if there is only one property

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

https://pastebin.com/y0wgcJn3

https://pastebin.com/1kP1BB5f

Upvotes: 0

Views: 265

Answers (1)

Gereon
Gereon

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

Related Questions