如何将字典转换为 Swift 中的顶级 JSON?

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

我在 Swift 中有这个模型:

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

转换为JSON时是否可以将属性移动到顶层?示例:

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

变成

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

首先,对静态键进行编码,然后将属性编码到同一个编码器中:

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)

    }
}

使用计算属性将对象转换为字典并对字典进行编码

extension EventModel {
    var asDictionary: [String: String] {
        var dictionary = attributes ?? [:]
        dictionary["evenType"] = eventType
        if let eventName = eventName { dictionary["eventName"] = eventName }
        return dictionary
    }
}

do {
    let data = try JSONEncoder().encode(model.asDictionary)
    if let s = String(data: data, encoding: .utf8) { print(s)}
} catch {
    print(error)
}

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