Skip to content

Parse a JSON Object Using Codable in Swift

Swift, Codable, JSON1 min read

The first step in using Codable to parse a JSON object is to define a Swift struct or class that conforms to the Codable protocol. This struct or class should reflect the structure of the JSON data you want to parse. For example, consider the following JSON object:

2 "name": "John Doe",
3 "age": 32,
4 "email": ""

To parse this JSON object using Codable, we can define a struct like this:

1struct User: Codable {
2 let name: String
3 let age: Int
4 let email: String

The properties in the User struct match the keys in the JSON object. By declaring the User struct as conforming to the Codable protocol, Swift will automatically generate the necessary code to encode and decode instances of the User struct from JSON data.

Once you have defined your Codable struct or class, you can parse a JSON object using the following code:

1let json = """
3 "name": "John Doe",
4 "age": 32,
5 "email": ""
9let data = .utf8)!
11do {
12 let user = try JSONDecoder().decode(User.self, from: data)
13 print(user)
14} catch {
15 print(error)

The above code converts the JSON string to a Data object using the data(using:) method. It then uses a JSONDecoder to decode the Data object into a User instance. The decode method throws an error if the JSON data is malformed or if it doesn't match the structure of the User struct. Therefore, we need to use a do-catch block to handle any errors that may occur during the decoding process.

It's worth noting that Codable can also handle more complex JSON structures, including nested objects, arrays, and optional values. For example, consider the following JSON object:

2 "name": "John Doe",
3 "age": 32,
4 "email": "",
5 "address": {
6 "street": "1 Main St",
7 "city": "San Francisco",
8 "state": "CA",
9 "zip": "94111"
10 }

To parse this JSON object, we can define a nested struct to represent the address:

1struct Address: Codable {
2 let street: String
3 let city: String
4 let state: String
5 let zip: String
8struct User: Codable {
9 let name: String
10 let age: Int
11 let email: String
12 let address: Address

With these nested structs, Codable can automatically parse the JSON object into instances of the User and Address structs.

In summary, Codable is a great tool for parsing JSON data in Swift. By conforming your structs or classes to the Codable protocol, you can easily decode JSON data into native Swift objects and leverage the power of the Swift language to handle your data.