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



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

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

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"人,"evenType":"type","eventName":"name","attribute2":"Two"}

相关内容

  • 没有找到相关文章

最新更新