Search code examples
jsonswiftencodable

Swift: custom key-value encoding with Encodable conformance in struct


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

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

Given this struct and the default Encodable conformance provided, JSON encoding produces

{
    key = abc;
    value = xyz;
}

whereas instead I'd like to to encode it to

{
    abc = xyz;
}

how do I conform this struct to Encodable to end up with this result?


Solution

  • Implement encode(to encoder: Encoder) and encode the struct as single dictionary

    struct Struct: Encodable {
        let key: String
        let value: String
        
        func encode(to encoder: Encoder) throws {
            var container = encoder.singleValueContainer()
            try container.encode([key:value])
        }
    }