Swift 4 Codable
Swift4 makes JSON serialization easier than ever. If you want an object to be encodable, Adapt to Encodable protocols. If you want an object to be decodable, adapt to Decodable protocols. Codable protocols is for objects that both encodable and decodable.
Automatic Encoding and Decoding
1 | struct Employee: Codable { |
Now this class can be serialize or deserialize to JSON. Isn’t that convenient? Also if you have an object as a property inside another object, conform to Codable too.
1 | struct Employee: Codable { |
The above class can also be serialize or deserialize to JSON.
Encoder and Decoder
Encoder works to turn Encodable objects to JSON serialized string. Decoder works to turn JSON serialized string into Decodable objects.
Here is how you encode:
1 | let jsonEncoder = JSONEncoder() |
Here is how you decode:
1 | let jsonDecoder = JSONDecoder() |
Renaming Properties With CodingKeys
If you want to have different keys then your property name in your serialized string, you will have to implement a CodingKey enum. Note that you will need to include all properties in the enum even if you don’t plan to rename all of them.
1 | struct Employee: Codable { |
Manual Encoding and Decoding
If in some case you want to alter the structure of the JSON not just rename the properties, you will need to write your own encoding and decoding logic.
For example, you don’t want to have the following JSON:
1 | { |
Instead you want the following JSON:
1 | { |
You will have to change the following in CodingKeys, the key enum case contains the key for the json. So you need to add case amount and case tax since they are both the key to the serialized string.
1 | struct Employee: Codable { |
For encode:
1 | extension Employee: Encodable { |
For decode
1 | extension Employee: Decodable { |
Inheritance of Encodable / Decodable
You have to override the encode or init:decoder in your subclass and call super before the regular instructions.
For example of encode: Code sample from Stack Overflow
1 | class BasicData { |
NOTE: When doing research, I found that there is some resource out there that passes container.superEncoder and container.superDecoder into the super class methods. For example: swift4 - Using Decodable in Swift 4 with Inheritance - Stack Overflow. However, when I try in my QuestIt project, I found that it will create a new subentry called super: { ... } in serialized JSON, but those are just redundant data because everything inside that super section is already exists in outside super. So that’s not a very good solution. I recommand to pass in encoder or decoder directly to super.
