Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. JSONDecoder / JSONEncoder

JSONDecoder / JSONEncoder

Swift's Foundation framework provides JSONDecoder and JSONEncoder, which let you convert between JSON data and Swift types. Both classes offer extensive options for customizing decoding strategies and encoding output.

Methods & Properties

Class / PropertyDescription
JSONDecoder().decode(_:from:)Decodes a Data value into the specified Codable type.
JSONEncoder().encode(_:)Encodes a Codable value into JSON Data.
decoder.keyDecodingStrategySpecifies how JSON key names are converted when decoding (e.g., .convertFromSnakeCase).
encoder.keyEncodingStrategySpecifies how property names are converted when encoding (e.g., .convertToSnakeCase).
decoder.dateDecodingStrategySpecifies how Date values are decoded (e.g., .iso8601).
encoder.dateEncodingStrategySpecifies how Date values are encoded (e.g., .iso8601).
encoder.outputFormattingSpecifies the formatting of the JSON output (e.g., .prettyPrinted).

Sample Code

import Foundation

// Decode snake_case JSON into a camelCase Swift type
struct Article: Codable {
    let articleId: Int
    let articleTitle: String
    let publishedAt: Date
    var isPublished: Bool
}

let json = """
{
    "article_id": 42,
    "article_title": "Introduction to Swift JSON",
    "published_at": "2026-03-06T12:00:00Z",
    "is_published": true
}
"""

let decoder = JSONDecoder()
decoder.keyDecodingStrategy   = .convertFromSnakeCase  // Auto-convert snake_case to camelCase
decoder.dateDecodingStrategy  = .iso8601               // Parse dates in ISO 8601 format

if let data = json.data(using: .utf8),
   let article = try? decoder.decode(Article.self, from: data) {
    print("ID: \(article.articleId)")
    print("Title: \(article.articleTitle)")
    print("Published at: \(article.publishedAt)")
}

// Encoding: Swift → JSON
let encoder = JSONEncoder()
encoder.keyEncodingStrategy   = .convertToSnakeCase    // Auto-convert camelCase to snake_case
encoder.dateEncodingStrategy  = .iso8601
encoder.outputFormatting      = .prettyPrinted

let newArticle = Article(
    articleId: 99,
    articleTitle: "New Article",
    publishedAt: Date(),
    isPublished: false
)

if let encoded = try? encoder.encode(newArticle),
   let jsonString = String(data: encoded, encoding: .utf8) {
    print("\nEncoded result:")
    print(jsonString)
}

// Decoding an array
let arrayJson = """
[{"article_id": 1, "article_title": "Article A", "published_at": "2026-01-01T00:00:00Z", "is_published": true},
 {"article_id": 2, "article_title": "Article 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("\nArticle list:")
    for a in articles {
        print("  \(a.articleId): \(a.articleTitle)")
    }
}

Notes

Using keyDecodingStrategy = .convertFromSnakeCase automatically maps snake_case JSON keys to camelCase Swift properties, so you do not need to define CodingKeys manually.

When a decoding error occurs, using try? silently returns nil without any details about the cause. During development, wrap the call in a do-catch block to inspect the error. dateDecodingStrategy applies to every Date property in the type. If your JSON contains dates in multiple formats, use .custom to handle each format individually.

For more on the Codable protocol, see Codable / Encodable / Decodable.

If you find any errors or copyright issues, please .