Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用swift 4创建嵌套json最优雅的方法是什么?_Json_Swift_Encodable - Fatal编程技术网

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

使用swift 4创建嵌套json最优雅的方法是什么?,json,swift,encodable,Json,Swift,Encodable,从这个只有一个参数的结构创建JSON最优雅的方法是什么 struct SessionStorage: Encodable { var value: String func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) /// the magic }

从这个只有一个参数的结构创建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字符串

{params:{value:{value}}

我不想创建嵌套结构。

有两种方法:

将字典编码为[字符串:会话存储]

使用信封结构

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

我认为这不是优雅的问题,而是效率的问题。优雅之处在于不指定encodeto和CodingKeys漂亮的阿凡达帽子:@Vyacheslav这是赢得的冬季狂欢节帽子之一。
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) }