展平嵌套结构并使用单键转换为 json

问题描述 投票:0回答:0

我有一个带有嵌套结构的对象,我想对它们进行编码,所以我有一个 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"
    }
}

我只是能够以某种方式对其进行编码,所以当我添加例如 元键下的应用程序属性,它将从 Platform

中删除先前添加的属性
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)
}
json swift struct encode codable
© www.soinside.com 2019 - 2024. All rights reserved.