Reputation: 199
Say I have the following struct:
struct Event: Codable {
var id: Int
.... // many non nested fields
}
In my application a user is allowed to create a list of events. Once the user is finished I'd like to pass that list to my server via a POST request.
In order to do so I need to create a valid JSON object that looks like this.
This is a list of Event
with a leading key of "events"
.
{ "events": [{"id": 1, ... more of the non nested fields ... },{ ... }]}
How can I setup my Event
object in such a way that JSONEncoder.encode(events)
will return the expected JSON above? I would really like to avoid having a CodingKey for each field because they encode,decode just fine expect in this circumstance. I'd also like to avoid nesting this Event
object inside another struct called Events
to get the desired result.
Upvotes: 1
Views: 179
Reputation: 63187
You can just encode a dictionary which associates your events
array to the key "events"
JSONEncoder.encode(["events": events])
Upvotes: 1