In the last post we went through a little sneak peak of how easy it is to work with JSON since Swift 4. Now let’s keep it up and see how to deal with custom keys and custom objects.
Custom keys
APIs often use snake case convention for naming keys (this_is_snake_case)… or even kebab case (this-is-kebab-case). Snake case is not a very Swifty thing because it doesn’t match the naming guidelines. Swift loves camel case (thisIsCamelCase). So if you get something like this:
{
"product_id": 1423,
"name": "Hockey Mask",
"color-name": "white",
"price-key-to-piss-the-developer-off": 39.90
}
it’s not a good practice to mirror those names so you should better create custom keys. Like this:
struct Product: Codable {
let productId: Int
let name: String
let colorName: String?
let price: Float
enum CodingKeys: String, CodingKey {
case productId = "product_id"
case name
case colorName = "color-name"
case price = "price-key-to-piss-the-developer-off"
}
}
- Lines 2 to 5. We set our object property names as they best fit our needs.
- Line 7. The keyword here is
CodingKeys
, which is aCoding Key
enumeration. It connects each property to a value in the encoded format. - Lines 8 to 11. For each property we define which key to use in the encoded format.
Here’s the output:
Product(productId: 1423, name: "Hockey Mask", colorName: Optional("white"), price: 39.9)
Custom objects
Let’s say we have this JSON:
{
"productId": 1423,
"name": "Hockey Mask",
"color": "white",
"price": {
"price": 39.90,
"currency": "USD",
"formatted": "39.90 USD"
}
}
It’s a very common scenario and, fortunately, the Codable
protocol makes our lives very easy: we just need to create an object Price
which conforms to the Codable
protocol as well and then use it as the type for our “price” property:
struct Price: Codable {
let price: Float
let currency: String
let formatted: String
}
struct Product: Codable {
let productId: Int
let name: String
let color: String?
let price: Price?
}
Here’s the output:
Product(productId: 1423, name: "Hockey Mask", color: Optional("white"), price: Optional(__lldb_expr_3.Price(price: 39.9, currency: "USD", formatted: "39.90 USD")))
You can use custom keys in custom objects as well, as explained above.
What’s next?
In the next post, we’ll talk about top level entities and arrays.