0
0
iOS Swiftmobile~20 mins

Codable protocol for JSON parsing in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: User List
This screen fetches a list of users from a JSON string and shows their names in a list.
Target UI
---------------------
|     User List      |
---------------------
| * Alice            |
| * Bob              |
| * Charlie          |
---------------------
Create a User struct that conforms to Codable with 'id' and 'name' properties.
Parse a JSON string containing an array of users into User objects.
Display the user names in a vertical list on the screen.
Show a loading text while parsing the JSON.
Starter Code
iOS Swift
import SwiftUI

struct UserListView: View {
    @State private var users: [User] = []
    @State private var isLoading = true

    var body: some View {
        VStack {
            Text("User List")
                .font(.title)
                .padding()

            if isLoading {
                Text("Loading users...")
            } else {
                List(users, id: \.id) { user in
                    Text(user.name)
                }
            }
        }
        .onAppear {
            // TODO: Parse JSON and update users
        }
    }
}

// TODO: Define User struct here

struct UserListView_Previews: PreviewProvider {
    static var previews: some View {
        UserListView()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
import SwiftUI

struct User: Codable, Identifiable {
    let id: Int
    let name: String
}

struct UserListView: View {
    @State private var users: [User] = []
    @State private var isLoading = true

    let jsonString = "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"},{\"id\":3,\"name\":\"Charlie\"}]"

    var body: some View {
        VStack {
            Text("User List")
                .font(.title)
                .padding()

            if isLoading {
                Text("Loading users...")
            } else {
                List(users) { user in
                    Text(user.name)
                }
            }
        }
        .onAppear {
            if let data = jsonString.data(using: .utf8) {
                do {
                    let decodedUsers = try JSONDecoder().decode([User].self, from: data)
                    users = decodedUsers
                } catch {
                    print("Failed to decode JSON: \(error)")
                }
            }
            isLoading = false
        }
    }
}

struct UserListView_Previews: PreviewProvider {
    static var previews: some View {
        UserListView()
    }
}

We defined a User struct that conforms to Codable and Identifiable so SwiftUI can uniquely identify each user in the list.

Inside onAppear, we convert the JSON string to Data and use JSONDecoder to decode it into an array of User objects.

We update the users state with the decoded array and set isLoading to false to show the list.

This approach cleanly parses JSON and updates the UI reactively.

Final Result
Completed Screen
---------------------
|     User List      |
---------------------
| * Alice            |
| * Bob              |
| * Charlie          |
---------------------
When the screen appears, it shows 'Loading users...' briefly.
Then it displays a scrollable list of user names: Alice, Bob, Charlie.
Stretch Goal
Add error handling UI to show a message if JSON parsing fails.
💡 Hint
Use a @State variable to track error messages and show a Text view if an error occurs.