JSONEncoder.KeyEncodingStrategy.convertToSnakeCase
A key encoding strategy that converts camel-case keys to snake-case keys.
Declaration
case convertToSnakeCaseDiscussion
Camel-case and snake-case are two common approaches for combining words when naming parts of an API. The Swift API Design Guidelines recommend using camel-case names. Some JSON APIs adopt snake-case; use this strategy when you encounter such an API.
This strategy uses uppercaseLetters and lowercaseLetters to determine the boundaries between words, and the system locale when converting uppercase letters to lowercase letters.
This strategy follows these steps to convert key names to snake-case:
Split the name into words, preserving leading or trailing underscores.
Insert an underscore between each word.
Convert the resulting string to lowercase.
The following examples show the result of applying this strategy:
feeFiFoFumConverts to:
fee_fi_fo_fumfee_fi_fo_fumConverts to:
fee_fi_fo_fumxmlContentsConverts to:
xml_contents
The example below shows how properties on the OlympicEventResult structure convert to snake-case when encoded as keys in a JSON object.
struct OlympicEventResult: Codable {
var goldWinner: String
var silverWinner: String
var bronzeWinner: String
}
let marathonResult = OlympicEventResult(goldWinner: "Light", silverWinner: "Sound", bronzeWinner: "Unladen Swallow")
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let encodeAndPrint = { print(String(data: try! encoder.encode(marathonResult), encoding: .utf8)!) }
encoder.keyEncodingStrategy = .convertToSnakeCase
encodeAndPrint()
/* Prints:
{
"bronze_winner" : "Unladen Swallow",
"gold_winner" : "Light",
"silver_winner" : "Sound"
}
*/