0
0
iOS Swiftmobile~20 mins

Custom decoder configuration in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: User Profile Decoder
This screen fetches and decodes a JSON user profile using a custom JSONDecoder configuration to handle date formats and key decoding strategy.
Target UI
-------------------------
| User Profile          |
|-----------------------|
| Name:                 |
| Email:                |
| Birthdate:            |
|                       |
| [Load Profile] Button |
-------------------------
Create a User struct conforming to Decodable with name, email, and birthdate properties.
Configure JSONDecoder to use ISO8601 date decoding strategy.
Configure JSONDecoder to convert snake_case keys to camelCase properties.
Add a button labeled 'Load Profile' that triggers JSON decoding from a hardcoded JSON string.
Display decoded user data on the screen after decoding.
Starter Code
iOS Swift
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") {
                // TODO: Add JSON decoding logic here
            }
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(8)
        }
        .padding()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
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.

Final Result
Completed Screen
-------------------------
| User Profile          |
|-----------------------|
| Name: Alice Johnson   |
| Email: alice@example.com |
| Birthdate: May 15, 1990|
|                       |
| [Load Profile] Button |
-------------------------
User taps 'Load Profile' button.
App decodes JSON with custom decoder settings.
User info appears below the title with formatted birthdate.
Stretch Goal
Add error message display below the button if JSON decoding fails.
💡 Hint
Use a @State String? variable to hold error messages and show a Text view conditionally.