1

I have the following struct that I send to an endpoint:

struct IdleAlarmRequest: Encodable {
    let idleAlarm: [IdleAlarmParameters]

    enum CodingKeys: String, CodingKey {
        case idleAlarm = "IdleAlarm"
    }
}

No matter what I do idleAlarm will always be written as idle_alarm in the resulting JSON string. This should be IdleAlarm as "objects" are PascalCased with this API, only fields should be snake_cased. Decodable works fine.

All of the other fields in all of the objects are snake_cased so if I don't use snake_case I need to add CodingKeys for hundreds of fields.

Lucas van Dongen
  • 9,328
  • 7
  • 39
  • 60

1 Answers1

1

There is no code in your question so I cannot fully understand what you are doing, consider editing it to add more details.

But I guess you are encoding your struct this way:

let request = IdleAlarmRequest(...)

let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
do {
    let data = try encoder.encode(request)
}
catch {

}

The convertToSnakeCase strategy convert your coding keys from camel-case to snake-case.

If you do not want this behavior you can remove the line.

EDIT: You can create a custom key encoding strategy.

encoder.keyEncodingStrategy = .custom { key -> CodingKey in
    // Your own code...
}
Florentin
  • 1,433
  • 2
  • 13
  • 22
  • 1
    Well there are hundreds of snake_cased fields and perhaps 10 PascalCased, so I would like to use CodingKeys for exceptional cases. – Lucas van Dongen Apr 25 '19 at 10:46
  • Unfortunately, this is not possible. If you use `convertToSnakeCase`, it will convert all your coding keys. You could try creating a custom key encoding strategy with a logic to ignore your 10 PascalCased keys, I edited my answer with an example. – Florentin Apr 26 '19 at 02:20