How do I decode and encode JSON with Codable in Swift?

In Swift, you can easily decode and encode JSON using the Codable protocol. This protocol is a type alias for the Encodable and Decodable protocols, enabling types to be encoded to and decoded from JSON effortlessly.

Encoding JSON

To encode a Swift object to JSON, you simply create an instance of JSONEncoder and call the encode method.

Decoding JSON

Similarly, to decode JSON into a Swift object, you create an instance of JSONDecoder and call the decode method.

Example

// Example Swift struct conforming to Codable struct User: Codable { var id: Int var name: String } // Encoding a User instance to JSON let user = User(id: 1, name: "John Doe") let encoder = JSONEncoder() if let jsonData = try? encoder.encode(user) { let jsonString = String(data: jsonData, encoding: .utf8) print(jsonString) // {"id":1,"name":"John Doe"} } // Decoding JSON back to a User instance let json = "{\"id\":1,\"name\":\"John Doe\"}" let decoder = JSONDecoder() if let jsonData = json.data(using: .utf8) { if let decodedUser = try? decoder.decode(User.self, from: jsonData) { print(decodedUser.name) // John Doe } }

Swift JSON Codable Encoding Decoding