— Swift, Codable, JSON — 1 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:
1{2 "name": "John Doe",3 "age": 32,4 "email": "johndoe@example.com"5}
To parse this JSON object using Codable, we can define a struct like this:
1struct User: Codable {2 let name: String3 let age: Int4 let email: String5}
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 = """2{3 "name": "John Doe",4 "age": 32,5 "email": "johndoe@example.com"6}7"""8
9let data = json.data(using: .utf8)!10
11do {12 let user = try JSONDecoder().decode(User.self, from: data)13 print(user)14} catch {15 print(error)16}
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:
1{2 "name": "John Doe",3 "age": 32,4 "email": "johndoe@example.com",5 "address": {6 "street": "1 Main St",7 "city": "San Francisco",8 "state": "CA",9 "zip": "94111"10 }11}
To parse this JSON object, we can define a nested struct to represent the address:
1struct Address: Codable {2 let street: String3 let city: String4 let state: String5 let zip: String6}7
8struct User: Codable {9 let name: String10 let age: Int11 let email: String12 let address: Address13}
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.