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.



FREE GUIDE: Parsing JSON in Swift - The Ultimate Cheat Sheet

Learn the fundamentals of JSON parsing in Swift, advanced decoding techniques, and tasks for app development

DOWNLOAD THE FREE GUIDE

The Foundation framework contains an old class called JSONSerialization, which was the standard way to decode JSON data before the Codable protocols were introduced.

The JSONSerialization class does not require custom Swift types to decode JSON data. Instead, it converts it into dictionaries, arrays, and other standard Swift types.

import Foundation

let data = """
{
	"name": "Tomatoes",
	"nutrition": {
		"calories": 22,
		"carbohydrates": 4.8,
		"protein": 1.1,
		"fat": 0.2
	},
	"tags": [
		"Fruit",
		"Vegetable",
		"Vegan",
		"Gluten free"
	]
}
""".data(using: .utf8)!

let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
let nutrition = json["nutrition"] as! [String: Any]
let carbohydrates = nutrition["carbohydrates"] as! Double
print(carbohydrates)
// Output: 4.8

The disadvantage of this approach is that the content of the resulting dictionaries and arrays is untyped, so you must force-cast any value to the appropriate type.

This produces a lot of boilerplate code, so it should be used sparingly. If the data you decode will be used across your app, you should create Codable types instead and use a JSONDecoder instance.

If you want a quick reference of code snippets to parse JSON data in Swift with or without Codable, together with other JSON parsing techniques, download my free cheat sheet below.

FREE GUIDE: Parsing JSON in Swift - The Ultimate Cheat Sheet

Learn the fundamentals of JSON parsing in Swift, advanced decoding techniques, and tasks for app development

DOWNLOAD THE FREE GUIDE

Leave a Comment