You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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.

1. Define a Custom Class That Matches Your JSON Structure

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; }
2. Fetch and Parse the JSON Data in MainWindow's Code-Behind

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}");
        }
    }
}
3. Set Up Your WPF DataGrid

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>
Quick Extra Tips
  • 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 replace JsonConvert.DeserializeObject with System.Text.Json.JsonSerializer.Deserialize).
  • Async is Key: Never use the synchronous GetString method—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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:42:31