对模型中没有嵌套 属性 的嵌套对象进行编码

Encoding a nested object that does not have nested property in its model

假设我有以下结构:

struct Event: Codable {
    var id: Int
    .... // many non nested fields
}

在我的应用程序中,允许用户创建事件列表。用户完成后,我想通过 POST 请求将该列表传递到我的服务器。

为此,我需要创建一个有效的 JSON 对象,如下所示。 这是 Event 的列表,前导键为 "events"

{ "events": [{"id": 1, ... more of the non nested fields ... },{ ... }]}

如何设置我的 Event 对象,使 JSONEncoder.encode(events) 将 return 上面预期的 JSON?我真的很想避免为每个字段使用 CodingKey,因为在这种情况下,它们编码、解码都很好。我还想避免将此 Event 对象嵌套在另一个名为 Events 的结构中以获得所需的结果。

您可以只编码一个字典,将您的 events 数组与键 "events"

相关联
JSONEncoder.encode(["events": events])