JSON Encoding and Decoding in Swift via Codable
The Basics
Codable
protocol in Foundation enables JSON encoding and decoding. In the example below, we have a simple point structure that includes Date. All you have to do to pass it to a JSONEncoder
is to make it compliant with the Codable
protocol. The Codable
protocol itself is defined as Encodable & Decodable
Note the dateEncodingStrategy
in the above example, this tells the encoder you how to format the Foundation Date
objects when converting to string. Decoding is pretty straight forward as well.
Make note of the .dateDecodingStrategy
on how to parse the string representation as Foundation Date
objects
Nested Structures
If your JSON has nested structures, create a model that represents it. Lets take the following example
Our GeoCoding service returns results by nesting them as a results array and a status message. First thing we do is create a structure to support the format of the top level. For this we create the GeocodingService
structure with the GeocodingResult
array and status
string. Each of the GeocodingResult
will contain the Geometry
and Location
structures. In the above example, we are only interested in the lat
and lng
and we can easily access them as show.
What if JSON Schema is different than my Model?
A very common problem with JSON parsing is the schema does not always exactly match your model. In the same Geocoding example above the formatted_address
is not very swifty. We would rather have our model say formattedAddress
. This is very easily accomplished by defining an enum at the level of nesting called CodingKeys
As you can see now the formatted_address
in JSON will be mapped to formattedAddress
in our GeocodingResult
. The only caveat here is if you define the CodingKeys
enum, all the keys at the level should be included as you are overwriting the default.