Parsing JSON in Swift: The Complete Guide [With Examples]

Parsing JSON data is fundamental to any iOS app that performs remote REST API calls.

Thanks to the Codable protocols introduced in Swift 4, Swift has a native and idiomatic way to parse JSON data.

Paired with the JSONDecoder class, the Decodable protocol allows straightforward JSON decoding in a few lines of code and more sophisticated techniques to handle all the possible data formats and edge cases.

Decoding JSON with Dynamic Types in Swift [With Codable]

JSON data is not always homogenous. There are instances in which a JSON object field can contain objects containing different information.

In such cases, the Swift type for the decoding must be determined dynamically.

Decode JSON with Dynamic Keys in Swift [Dictionaries and Arrays]

JSON object with dynamic keys presents a specific challenge when decoding data in Swift because stored properties cannot represent dynamic keys.

However, it’s still possible to decode JSON with dynamic keys using the Decodable protocol into dictionaries or arrays by implementing structures that conform to the CodingKey protocol.

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.