如果 JSON 响应 returns 如果只有一个 属性 字典,我的 Codable 结构应该是什么样子

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

由于很多人将数组与字典混淆,我找不到任何相关信息,但就我而言,当只有一个 [=25] 时,JSON 响应是一本字典=] 否则它将是一个数组。那我该怎么做呢?

    ....

    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"
        }
    }

    ....

字典和数组响应示例

https://pastebin.com/y0wgcJn3

https://pastebin.com/1kP1BB5f

您可以实现自定义 init 方法,将“单个”MessageDetail 转换为单元素数组:

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)
        }
    }
}