Skip to content

Instantly share code, notes, and snippets.

@dkw5877
Created March 26, 2019 23:07
Show Gist options
  • Save dkw5877/9bec3f94e8cfd6660084743f3f6a8231 to your computer and use it in GitHub Desktop.
Save dkw5877/9bec3f94e8cfd6660084743f3f6a8231 to your computer and use it in GitHub Desktop.
Key Encoding and Decoding in Swift
let object = ["keyOne":"Bengal tiger", "keyTwo":"Siberian tiger", "keyThree ":"white rhino", "keyFour":"African elephant"]
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
encoder.outputFormatting = [.sortedKeys, .prettyPrinted]
let encoded = try? encoder.encode(object)
print(String(data: encoded!, encoding: .utf8)!)
//output
{
"key_four" : "African elephant",
"key_one" : "Bengal tiger",
"key_three " : "white rhino",
"key_two" : "Siberian tiger"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment