Swift:在结构中具有可编码一致性的自定义键值编码

时间:2020-07-23 16:42:15

标签: json swift encodable

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才能得到此结果?

1 个答案:

答案 0 :(得分: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])
    }
}