-1
struct Struct: Encodable {
  let key: String
  let value: String
}

let aStruct = Struct(key: "abc", value: "xyz")

鉴于此结构和Encodable提供的默认一致性,JSON 编码产生

{
    key = abc;
    value = xyz;
}

而相反,我想将其编码为

{
    abc = xyz;
}

我如何使这个结构符合Encodable这个结果?

4

1 回答 1

3

实现encode(to encoder: Encoder)结构并将其编码为单个字典

struct Struct: Encodable {
    let key: String
    let value: String
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode([key:value])
    }
}
于 2020-07-23T16:52:41.873 回答