Complete Guide to Codable — Encodable
A quick and easy way to convert yourData models
to JSON
object
Codable
was introduced in Swift 4
which helps you convert your JSON to your model and model back to a JSON object. Codable
is a typalias of Decodable
and Encodable
protocols. Codable
is similar to Serialization in Java
In this tutorial, we will only be covering
Encodable
in-depth
Encodable
Encodable
is used for converting your data model to JSON object with the help ofJsonEncoder
Let’s take a simple example of how to encode your data-model to the JSON object
- Create your data model and conform to Encodable
- Create an instance of
JsonEncoder
and useencode(_:)
to encode thePhotoFeed
object to aJSON
object.
Hurray! And just by writing a few lines of code, you have your data-model mapped to JSON.
What else can Encodable do?
Optional keys in Encodable
JsonEncoder
will avoid adding keys to theJSON
object ONLY if the variables are optional and their respective values are nil
. In the below example, we have made feedDate
an optional variable and have set its value as nil. This will avoid adding the key to theJSON
object.
CodingKey
Let's say the server request needs the JSON keys
in snake_case
instead of camel_case
. This can be made possible with the help of CodingKey
.
CodingKey
tells the JSONEncoder
to map the variables present in the data-model
to the keys present in CodingKeys
. In the below example we have renamed the keys in enum CodingKeys from feedKey
→feed_key
, feedUrl
→ feed_url
and feedDate → feed_date
.
Handle Nested Data
Encoding nested data is as simple as encoding a simple data model. Let’s say the API server requests start asking you to send location
along with the feed. You can add the location in your data-model which will conform to Encodable
. You can add the new Location struct in your PhotoFeed
or as a new struct
outside the PhotoFeed.
Customizing Encoding
OutputFormatting
This value tells the encoder to show how the encoded JSON object would be laid out; like the element order and its readability.
1. prettyPrinted
: It shows formatted JSON object with white space and indentation that makes it easy to read.
2. sortedKeys
: It shows formatted JSON that sorts keys in lexicographic order.
Encoding Strategy
Most of the time the server requests not always follow the camelCase
naming convention. There is a good chance that you may have a request that follows snake_case.
We can set the encoding strategy
that determines how data-model
variables are encoded in a JSON object. Let’s take an example:
1.useDefaultKeys
: It's a default strategy. It will use the same keys for encoding that have been mentioned in the data-model.
2.convertFromSnake
: It will convert the camel-case🐫
variable from your data-model to snake-case🐍
while encoding the JSON object.
3.custom
: You can have your custom implementation where you can choose the name of all the keys you have in the JSON object. This custom closure is called for each variable that is encoded.
We have taken an example where we prefix photo
to all the JSON encoded objects.
Encoding Dates
JsonEncoder
supports encoding dates to the JSON object. Below are the list of strategies that you can use for encoding dates.
1.deferredToDate
: Number of seconds elapsed since 1st Jan 2001
represented in double
. An extremely rare chance you would be using this.
2. iso8601
: This is the most widely used date-format. Use this link to understand more about date-format used under iso8601
3. formatted(DateFormatter)
: You can add a custom DateFormatter
with the required dateFormat that you wish to encode your JSON object.
4.custom((Date, Encoder) -> Void)
: This strategy helps you write custom code for parsing your dates to the encoded JSON object. Let’s take an example where you have to send multiple date formats in the JSON object.
5.millisecondsSince1970
: It encodes dates in milliseconds since midnight UTC on January 1, 1970
6.secondsSince1970
: It encodes dates in seconds since midnight UTC on January 1st, 1970
Encoding Raw Data
JsonEncoder
supports strategies for encoding your raw data into JSON objects. Here is a list of supported data encoding strategies
1.base64
: encodes data using Base 64
2.custom((Data, Encoder)
: encodes data using a custom function implemented by you.
By now you already got a gist of how the default custom encoding works and how would you use them. Still find it difficult to understand, comment below and I will add gist for you
Encoding Exceptional Numbers
This policy is used by a JsonEncoder
when it encounters exceptional floating-point values. Say if you have to update the server that some values are not-a-number NaN
and have infinite values that might need to be handled differently. Here is how you handle nan
, +veInfinity
and -veInfinity
That’s pretty much you what you get in Encodable
🙌
Did I miss a use-case? Let me know in the comments below!