使用 swift 4 创建嵌套 json 的最优雅的方法是什么?

What is the most elegant way to create nested json using swift 4?

从只有一个参数

的结构中创建JSON的最优雅的方法是什么
    struct SessionStorage: Encodable {
        var value: String

        func encode(to encoder: Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
        /// the magic
        }

        enum CodingKeys: String, CodingKey {
            case params
        }
    }

进入这个 JSON-string?

{"params": {"value": "{value}"}}

我不想创建嵌套结构。

两种方式:

  1. 将字典编码为[String: SessionStorage]

    struct SessionStorage: Encodable {
        var value: String
    }
    
    let session = SessionStorage(value: "Foo")
    
    do {
        let jsonData = try JSONEncoder().encode(["params" : session])
        print(String(data: jsonData, encoding: .utf8)!)
    } catch { print(error) }
    
  2. 使用信封结构

    struct Envelope : Encodable {
        let params : SessionStorage
    }
    
    
    struct SessionStorage: Encodable {
        var value: String
    }
    
    let envelope = Envelope(params : SessionStorage(value: "Foo"))
    
    do {
        let jsonData = try JSONEncoder().encode(envelope)
        print(String(data: jsonData, encoding: .utf8)!)
    } catch { print(error) }
    

恕我直言,这不是优雅的问题,而是效率的问题。优雅在于不指定 encode(toCodingKeys