Sometimes data from the internet or files needs special rules to be read correctly. Custom decoder configuration helps you tell your app how to understand that data.
0
0
Custom decoder configuration in iOS Swift
Introduction
When JSON keys don't match your Swift property names.
When dates or numbers come in a format that needs special parsing.
When you want to ignore some data fields during decoding.
When you want to handle missing or extra data gracefully.
Syntax
iOS Swift
let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let object = try decoder.decode(MyType.self, from: jsonData)
You create a JSONDecoder instance to start decoding.
Use keyDecodingStrategy to change how keys are matched.
Examples
This converts JSON keys like
first_name to Swift properties like firstName.iOS Swift
let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let user = try decoder.decode(User.self, from: data)
This tells the decoder to read dates in ISO 8601 format.
iOS Swift
let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let event = try decoder.decode(Event.self, from: data)
This shows how to write your own rule to change keys during decoding.
iOS Swift
struct AnyKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) { self.stringValue = stringValue; self.intValue = nil }
init?(intValue: Int) { self.stringValue = ""; self.intValue = intValue }
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom { keys in
// Custom logic to change keys
return AnyKey(stringValue: keys.last!.stringValue.uppercased())!
}
let item = try decoder.decode(Item.self, from: data)Sample App
This example shows how to decode JSON with snake_case keys into a Swift struct with camelCase properties using a custom decoder configuration.
iOS Swift
import Foundation struct User: Decodable { let firstName: String let lastName: String } let json = "{\"first_name\": \"Jane\", \"last_name\": \"Doe\"}".data(using: .utf8)! let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let user = try decoder.decode(User.self, from: json) print("First name: \(user.firstName), Last name: \(user.lastName)")
OutputSuccess
Important Notes
Custom decoder settings help your app understand data that doesn't match your code exactly.
Always handle errors when decoding because data might be missing or wrong.
You can combine multiple strategies like key and date decoding for complex data.
Summary
Custom decoder configuration lets you control how data is read into your app.
Use it to fix mismatches between data keys and your code properties.
It makes your app more flexible and able to handle different data formats.