import SwiftUI
struct User: Decodable {
let name: String
let email: String
let birthdate: Date
}
struct ContentView: View {
@State private var user: User? = nil
var body: some View {
VStack(spacing: 20) {
Text("User Profile")
.font(.title)
.bold()
Text("Name: \(user?.name ?? "")")
Text("Email: \(user?.email ?? "")")
Text("Birthdate: \(user != nil ? DateFormatter.localizedString(from: user!.birthdate, dateStyle: .medium, timeStyle: .none) : "")")
Button("Load Profile") {
let json = """
{
\"name\": \"Alice Johnson\",
\"email\": \"alice@example.com\",
\"birthdate\": \"1990-05-15T00:00:00Z\"
}
"""
guard let jsonData = json.data(using: .utf8) else { return }
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let decodedUser = try decoder.decode(User.self, from: jsonData)
user = decodedUser
} catch {
print("Decoding error: \(error)")
}
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
.padding()
}
}This solution creates a User struct that matches the JSON keys but uses camelCase property names. The JSONDecoder is configured with dateDecodingStrategy = .iso8601 to parse the birthdate string into a Date object. The keyDecodingStrategy = .convertFromSnakeCase automatically converts JSON keys like birthdate or snake_case keys to camelCase properties in Swift.
When the user taps the "Load Profile" button, the app decodes the hardcoded JSON string and updates the UI with the user's name, email, and formatted birthdate. This demonstrates how to customize decoding behavior to handle common JSON formats easily.