-1
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?

Ilias Karim
  • 4,798
  • 3
  • 38
  • 60

1 Answers1

3

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])
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361