我有一个带有嵌套结构的对象,我想对它们进行编码,所以我有一个 json,其中这些结构的属性在 json 中的相同键下。
例如,
struct Payload: Codable {
let meta: Meta
enum CodingKeys: String, CodingKey {
case meta = "mm"
}
}
struct Meta: Codable {
let application: Application?
let platform: Platform?
let device: Device?
}
struct Application: Codable {
let name: String
let version: String
}
struct Platform: Codable {
let type: String
}
struct Device: Codable {
let system: String
}
所以我希望 JSON 看起来像这样:
{
"mm": {
"name": "A"
"version": "B"
"type": "C"
"system": "D"
}
}
我只是能够以某种方式对其进行编码,所以当我添加例如 元键下的平台属性,它将删除应用程序对象之前添加的属性。
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(meta.application, forKey: .meta)
// will remove previously added properties from application
try container.encodeIfPresent(meta.platform, forKey: .meta)
}
如果看起来不酷,但如果你想加入来自不同级别的多个键/值对,你必须手动创建字典
struct Payload: Encodable {
let meta: Meta
enum CodingKeys: String, CodingKey {
case meta = "mm"
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
let dictionary = [
"name": meta.application?.name ?? "Unknown name",
"version": meta.application?.version ?? "Unknown version",
"type": meta.platform?.type ?? "Unknown type",
"system": meta.device?.system ?? "Unknown system"
]
try container.encode(dictionary, forKey: .meta)
}
}