Search code examples
jsonswiftdictionaryjsonencoder

How do I convert a dictionary to top level JSON in Swift?


I have this model in Swift:

struct EventModel: Codable {
    var eventType: String
    var eventName: String?
    var attributes: [String: String]?
}

Is it possible to move the attributes to the top level when I convert it to JSON? Example:

var model = EventModel(eventType: "type", 
                       eventName: "name", 
                       attributes: ["attribute1": "One", "attribute2": "Two"]) 

becomes

{
   "eventType" : "type",
   "eventName" : "name",
   "attribute1" : "One",
   "attribute2" : "Two"
}

Solution

  • First, encode the static keys, then encode the attributes into the same encoder:

    extension EventModel: Encodable {
        enum CodingKeys: CodingKey {
            case eventType, eventName
        }
    
        func encode(to encoder: Encoder) throws {
            // Encode the normal stuff
            var container = encoder.container(keyedBy: CodingKeys.self)
            try container.encode(eventType, forKey: .eventType)
            try container.encode(eventName, forKey: .eventName)
    
            // Then have the attributes dictionary encode itself
            try attributes?.encode(to: encoder)
    
        }
    }