Swift Codable – JSON Parser

Tram Ho

Codeable is a protocol used to convert a Swift object to a Data type. Codeable is a type alias for Encodealbe and Decodable protocal. This is an official and easy-to-use protocal that parsing JSON object from the server into a Swift Object.

Encodable is often used when the Swift object must be serialized and sent to the server. On the other hand, Decodable is used when JSON from Server must be deserialised.

Furthermore, custom objects conform Codable can now be saved and retrieved from UserDefaults directly in just 3 steps. Save a lot of time.

Basic parsing – Simple JSON

Let’s take the above JSON as an example and try to parse it into a Swift object. It has 4 fields of types: String, Int, Double and Int Array. They are all common types in JSON.

By creating a conform Codable object, JSON can decode directly into a Swift object.

By default, the variable name in the swift structure will map with the key name in JSON.

Key customisation

According to the coding convention, snake case (eg foo_key) is usually used in JSON but camel case (eg fooKey) is commonly used in Swift. Hence, Apple introduced a CodeingKey protocal that provides the ability to customize key names when we parse JSON.

Encoding customisation

To reduce traffic to the server, only the required fields can be Serialized and sent to the server, encoding (to encoder: Encoder) provides the ability to customize serialization and ignore redundant fields. In the above example, only strProp and intProp are serialized and doubleProp and intArrayProp are ignored.

Share the news now

Source : Viblo