Caution
お使いのブラウザはJavaScriptが実行できない状態になっております。
当サイトはWebプログラミングの情報サイトの為、
JavaScriptが実行できない環境では正しいコンテンツが提供出来ません。
JavaScriptが実行可能な状態でご閲覧頂くようお願い申し上げます。
JSONDecoder / JSONEncoder
SwiftのFoundationフレームワークの『JSONDecoder』『JSONEncoder』を使うと、JSON データと Swift の型を相互変換できます。デコード戦略やエンコードオプションのカスタマイズも豊富です。
メソッド・プロパティ一覧
| クラス / プロパティ | 概要 |
|---|---|
| JSONDecoder().decode(_:from:) | Data を指定した Codable 型にデコードします。 |
| JSONEncoder().encode(_:) | Codable な値を JSON の Data に変換します。 |
| decoder.keyDecodingStrategy | JSONキー名の変換方式を設定します(.convertFromSnakeCase 等)。 |
| encoder.keyEncodingStrategy | プロパティ名の変換方式を設定します(.convertToSnakeCase 等)。 |
| decoder.dateDecodingStrategy | Date の復元方式を設定します(.iso8601 等)。 |
| encoder.dateEncodingStrategy | Date の変換方式を設定します(.iso8601 等)。 |
| encoder.outputFormatting | JSON の出力形式を設定します(.prettyPrinted 等)。 |
サンプルコード
import Foundation
// snake_case の JSON を camelCase の Swift 型にデコード
struct Article: Codable {
let articleId: Int
let articleTitle: String
let publishedAt: Date
var isPublished: Bool
}
let json = """
{
"article_id": 42,
"article_title": "Swift JSON 入門",
"published_at": "2026-03-06T12:00:00Z",
"is_published": true
}
"""
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase // snake → camel 自動変換
decoder.dateDecodingStrategy = .iso8601 // ISO 8601 形式で Date に変換
if let data = json.data(using: .utf8),
let article = try? decoder.decode(Article.self, from: data) {
print("ID: \(article.articleId)")
print("タイトル: \(article.articleTitle)")
print("公開日: \(article.publishedAt)")
}
// エンコード: Swift → JSON
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase // camel → snake 自動変換
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = .prettyPrinted
let newArticle = Article(
articleId: 99,
articleTitle: "新しい記事",
publishedAt: Date(),
isPublished: false
)
if let encoded = try? encoder.encode(newArticle),
let jsonString = String(data: encoded, encoding: .utf8) {
print("\nエンコード結果:")
print(jsonString)
}
// 配列のデコード
let arrayJson = """
[{"article_id": 1, "article_title": "記事A", "published_at": "2026-01-01T00:00:00Z", "is_published": true},
{"article_id": 2, "article_title": "記事B", "published_at": "2026-02-01T00:00:00Z", "is_published": false}]
"""
if let data = arrayJson.data(using: .utf8),
let articles = try? decoder.decode([Article].self, from: data) {
print("\n記事一覧:")
for a in articles {
print(" \(a.articleId): \(a.articleTitle)")
}
}
概要
『keyDecodingStrategy = .convertFromSnakeCase』を使うと、JSON の snake_case キーを Swift の camelCase プロパティに自動変換できます。CodingKeys を個別に定義する手間が省けます。
デコード時にエラーが発生した場合、『try?』では nil になるだけで原因がわかりません。デバッグ時は do-catch で受け取り、エラーの詳細を確認してください。dateDecodingStrategy は JSON 中の全 Date 型に適用されます。複数の日付フォーマットが混在する場合は .custom でカスタマイズが必要です。
Codable プロトコルの詳細についてはCodable / Encodable / Decodableを参照してください。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。