Codable in Swift

One of the main reason why we use codable in swift is it makes easy to create model objects and map JSON objects to the model objects. The simplest way to make a type codable is to declare its properties using types that are already Codable. These types include standard library types like String, Int, Double, and Foundation types like Date, Data, and URL.

Let's explore the few usages of codable in swift.

Photo by Chris Ried on Unsplash

I will walk you through some examples.

Example 1: Assume our model class properties have the exact same name as in JSON

Let's create a model class for the user and parse JSON to the user model. JSON is given below.

Let's create a model class for this JSON.

Using JSONDecoder we can decode JSON and store in the model class.

Example 2: Assume our model class properties have some difference from keys used in JSON

If the keys used in your serialized data format don’t match the property names from your data type, provide alternative keys by specifying String as the raw-value type for the CodingKeysenumeration. The string you use as a raw value for each enumeration case is the key name used during encoding and decoding.

In model class instead of “firstName” and “lastName” we need to use “userfirstname” & “userlastname”. Then our model class will look like given below.

Example 3: If the structure of the model class is different from the structure of JSON then we do manual encoding and decoding

Decode JSON
Encode JSON

Example 4: Complex JSON ( Ex: two level json)

Finally, convert the model to JSON back. we can do it by using JSONEncoder().



iOS Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store