Introduction to Working with JSON in Swift
JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in mobile and web development. For beginner Swift (iOS/macOS) developers, the ability to work with JSON is an essential skill. In this article, we will cover two main approaches: the classic JSONSerialization and the modern Codable protocol. You will learn how to fetch data from the network, parse it, and convert it back to JSON for sending to the server.
Whether you are building a weather app, a to-do list, or a social network — JSON will be your faithful companion. Let's start with a simple example and gradually move to more complex scenarios.
JSON Basics in Swift: Structure and Data Types
Before writing code, it's important to understand what JSON looks like. In Swift, JSON is represented as dictionaries ([String: Any]) and arrays ([Any]). The main data types in JSON are:
- Strings — enclosed in double quotes (
"Hello") - Numbers — integers and floating-point (
42,3.14) - Booleans —
trueorfalse - Arrays — ordered lists of values (
[1, 2, 3]) - Objects — unordered collections of key-value pairs (
{"key": "value"}) - null — empty value
In Swift, it is convenient to use built-in data structures to represent JSON. Consider an example of a simple JSON object:
{ "name": "Ivan", "age": 25, "isStudent": false, "hobbies": ["reading", "programming"]}Now let's see how to work with this format in Swift code.
Parsing JSON with JSONSerialization (Classic Method)
Before the Codable protocol, developers used the JSONSerialization class. This method is still relevant, especially when the JSON structure is unknown in advance or is very dynamic.
Basic Parsing Example
Suppose we have a JSON string that needs to be converted into Swift objects:
let jsonString = """{ "name": "Maria", "age": 30, "isEmployed": true}"""
if let jsonData = jsonString.data(using: .utf8) { do { if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] { let name = dictionary["name"] as? String ?? "Unknown" let age = dictionary["age"] as? Int ?? 0 let isEmployed = dictionary["isEmployed"] as? Bool ?? false print("Name: \\(name), Age: \\(age), Employed: \\(isEmployed)") } } catch { print("JSON parsing error: \\(error.localizedDescription)") }}Note: after obtaining the dictionary, we explicitly cast each element to the required type. This can be inconvenient with a large number of fields.
Working with Arrays in JSON
JSON often contains arrays of objects. Let's look at an example with an array of users:
let jsonArrayString = """[ {"name": "Anna", "age": 22}, {"name": "Peter", "age": 28}]"""
if let data = jsonArrayString.data(using: .utf8) { do { if let users = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] { for user in users { let name = user["name"] as? String ?? "" let age = user["age"] as? Int ?? 0 print("\\(name): \\(age) years old") } } } catch { print("Error: \\(error)") }}The JSONSerialization method is simple but requires a lot of manual type casting. For modern projects, Apple recommends using Codable.