Decoding and Flattening Nested JSON with Codable

JSON data is rarely flat and often contains nested objects.

Nested JSON data can be decoded in Swift using the Decodable protocol and the JSONDecoder class.

However, how you decode nested JSON objects depends on the final result you want to obtain.

Coding Keys in Swift with Decodable: How and When to Use Them

You can easily parse JSON data in Swift by creating a Decodable type that matches the structure of a JSON object.

However, we often need to decode JSON data that does not match the model types of our apps. In those cases, we need to control the decoding using coding keys.

Parse JSON from an API URL in Swift [Codable and URLSession]

Fetching and parsing the JSON data returned by a URL is straightforward in Swift, thanks to the JSONDecoder and URLSession classes of the Foundation framework.

Parse JSON in Swift without Codable [Arrays and Dictionaries]

Since Swift 4, the recommended way to parse JSON data is to use the Codable protocols with the JSONEncoder and JSONDecoder classes.

However, this method requires creating Swift model types that match the JSON data structure you need to decode.

Sometimes, you might want to avoid creating extra Swift types if you only need to read some of the information in the JSON data locally.

Reading a JSON File in Swift [Bundle and Documents Directory]

Apps often need to read the content of JSON files for different reasons.

You can save static JSON data inside an Xcode project to populate your app or use it in SwiftUI previews.

Apps can also save data inside the device’s documents directory.

Swift Data to JSON String: Formatting and Pretty Printing

JSON data is often not human-readable because web servers strip all white space to save bandwidth.

Converting JSON data into a formatted string helps build decodable Swift types and is useful for debugging, saving data to a JSON File, and writing unit tests for an app’s JSON output.

Date decoding strategies in Swift [with Examples]

The Date type is a Codable type in Swift. However, dates are not straightforward to decode, like other types conforming to the Codable protocol, because the default format used by JSONDecoder is not standard in JSON.

Dates can be encoded using different formats in JSON data. To handle all these formats, the JSONDecoder class has a  dateDecodingStrategy property, which can be configured with several decoding strategies according to the date format you must decode.