繁体   English   中英

使用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字符串?

{"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 😉

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM