使用RestSharp在C#中为WPF DataGrid填充JSON数据
Hey there! I totally get how frustrating it can be when you're new to a tech stack and can't find straight answers after days of digging. Let's walk through this step by step—you'll have that DataGrid populated in no time.
First, you need a class that mirrors the data structure returned by your web service. Let's say your web service sends back a JSON array like this:
[{"Id":1,"FullName":"Doug C.","UserEmail":"doug@example.com"},{"Id":2,"FullName":"Jane Doe","UserEmail":"jane@example.com"}]
You'll create a class with properties that match those JSON keys (case matters if you're using default serializer settings):
// Make sure you've installed the Newtonsoft.Json NuGet package first (super common for WPF) public class AppUser { public int Id { get; set; } public string FullName { get; set; } public string UserEmail { get; set; } }
If your JSON uses different key names (like user_id instead of Id), just add the JsonProperty attribute to map them:
[JsonProperty("user_id")] public int Id { get; set; }
Next, we'll use HttpClient to call the web service, then convert the JSON response into a list of your custom class. We'll use async/await here to avoid freezing the UI—super important for WPF apps!
Here's the code for your MainWindow.xaml.cs:
using Newtonsoft.Json; using System.Collections.Generic; using System.Net.Http; using System.Windows; public partial class MainWindow : Window { // Reuse HttpClient instead of creating a new one each time private readonly HttpClient _httpClient = new HttpClient(); public MainWindow() { InitializeComponent(); // Trigger data load when the window finishes loading Loaded += MainWindow_Loaded; } private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { try { // Replace this with your actual web service URL string jsonResponse = await _httpClient.GetStringAsync("https://your-web-service-endpoint.com/api/users"); // Convert the JSON array into a list of your custom class List<AppUser> userList = JsonConvert.DeserializeObject<List<AppUser>>(jsonResponse); // Bind the list to your DataGrid UserDataGrid.ItemsSource = userList; } catch (Exception ex) { // Show a friendly error message if something goes wrong (network issues, bad JSON, etc.) MessageBox.Show($"Oops, something went wrong loading data: {ex.Message}"); } } }
Now head over to your MainWindow.xaml to define the DataGrid. For simplicity, you can let it auto-generate columns (great for testing), or define them manually for more control:
Auto-Generated Columns (Quick Setup)
<DataGrid x:Name="UserDataGrid" AutoGenerateColumns="True" Margin="15" IsReadOnly="True" RowHeaderVisibility="Collapsed"/>
Manual Columns (More Control Over Headers/Formatting)
<DataGrid x:Name="UserDataGrid" Margin="15" IsReadOnly="True" RowHeaderVisibility="Collapsed"> <DataGrid.Columns> <DataGridTextColumn Header="User ID" Binding="{Binding Id}" Width="Auto"/> <DataGridTextColumn Header="Full Name" Binding="{Binding FullName}" Width="*"/> <DataGridTextColumn Header="Email" Binding="{Binding UserEmail}" Width="*"/> </DataGrid.Columns> </DataGrid>
- NuGet Package Note: If you don't have Newtonsoft.Json installed, right-click your project → Manage NuGet Packages → Search for "Newtonsoft.Json" and install it. For .NET 5+, you can also use the built-in
System.Text.Json(just replaceJsonConvert.DeserializeObjectwithSystem.Text.Json.JsonSerializer.Deserialize). - Async is Key: Never use the synchronous
GetStringmethod—it'll lock up your UI until the request finishes. - Test the JSON: If you're getting deserialization errors, copy the JSON response into a tool like JSON Viewer to double-check it matches your class structure.
内容的提问来源于stack exchange,提问作者Doug C.

