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.