Codable / Encodable / Decodable
Swift's Codable protocol makes it easy to encode and decode structs and classes to and from JSON. It is a typealias that combines Encodable and Decodable.
Method List
| Class / Method | Description |
|---|---|
| Codable | A protocol that combines Encodable and Decodable. |
| JSONEncoder().encode(_:) | Converts an Encodable value into JSON Data. |
| JSONDecoder().decode(_:from:) | Decodes JSON Data into the specified type. |
| CodingKeys | Defines the mapping between property names and JSON key names. |
| encoder.outputFormatting | Sets the output format (e.g., prettyPrinted). |
| encoder.dateEncodingStrategy | Sets the strategy for encoding Date values. |
Sample Code
import Foundation
// A struct that conforms to Codable
struct User: Codable {
let id: Int
let name: String
let email: String
var isActive: Bool
}
// Encode: Swift → JSON
let user = User(id: 1, name: "Alice", email: "alice@example.com", isActive: true)
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // Human-readable format
if let jsonData = try? encoder.encode(user),
let jsonString = String(data: jsonData, encoding: .utf8) {
print("JSON:")
print(jsonString)
}
// Decode: JSON → Swift
let jsonString = """
{
"id": 2,
"name": "Bob",
"email": "bob@example.com",
"isActive": false
}
"""
let decoder = JSONDecoder()
if let data = jsonString.data(using: .utf8),
let decodedUser = try? decoder.decode(User.self, from: data) {
print("\nDecoded: \(decodedUser.name) (\(decodedUser.email))")
}
// CodingKeys: mapping between JSON key names and property names
struct Article: Codable {
let articleId: Int
let articleTitle: String
enum CodingKeys: String, CodingKey {
case articleId = "article_id" // snake_case → camelCase
case articleTitle = "article_title"
}
}
let articleJson = """
{"article_id": 10, "article_title": "Swift入門"}
"""
if let data = articleJson.data(using: .utf8),
let article = try? decoder.decode(Article.self, from: data) {
print("Article: \(article.articleTitle) (ID: \(article.articleId))")
}
Overview
If the property names in your type match the keys in the JSON, adopting Codable is all you need — encoding and decoding happen automatically. When customization is required, define a CodingKeys enum.
To map snake_case JSON keys to camelCase properties, you can either handle each key individually in CodingKeys, or use decoder.keyDecodingStrategy = .convertFromSnakeCase. If decoding fails, an exception is thrown. Use try? to get nil on failure, or use do-catch to retrieve detailed error information.
For the basics of protocols, see Protocol Basics / Conformance.
If you find any errors or copyright issues, please contact us.