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

Windows Forms C#反序列化后JSON数据无法在DataGridView显示

问题解决步骤

1. 核心问题分析

  • 你的PostResponse类和API返回的JSON结构完全不匹配:API返回的是包含message和products数组的对象,但你的PostResponse只定义了单个产品的字段。
  • DataGridView需要绑定集合类型(比如List<T>),而你直接绑定了单个对象,这会导致控件显示异常。

2. 修正实体类结构

根据API返回的JSON,创建正确的实体类:

// 根响应类,对应API返回的整个JSON结构
public class ApiResponse
{
    public string message { get; set; }
    public List<Product> products { get; set; }
}

// 单个产品类
public class Product
{
    public int id { get; set; }
    public string title { get; set; }
    public string description { get; set; }
    public int situation { get; set; }
    public string type_name { get; set; }
    public int type_id { get; set; }
    public List<Feature> features { get; set; }
}

// 产品特性类
public class Feature
{
    public int products_type_feature_id { get; set; }
    public string feature_name { get; set; }
    public string feature_unit_name { get; set; }
    public string feature { get; set; }
}

3. 修正Button点击事件代码

替换错误的反序列化逻辑,绑定products集合到DataGridView,同时正确使用异步方法:

private async void button1_Click(object sender, EventArgs e)
{
    try
    {
        var postData = new PostData
        {
            id = 5,
            title = "yeni",
            description = "yenidesc",
            type_name = "yenitype"
        };

        using var client = new HttpClient();
        client.BaseAddress = new Uri("-i_know_that_my_uri_should_be_here-");

        var json = JsonConvert.SerializeObject(postData);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await client.PostAsync("products", content);

        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseContent);
            
            // 绑定products集合到DataGridView
            dataGridView1.DataSource = apiResponse.products;
        }
        else
        {
            MessageBox.Show("Hata: " + response.StatusCode);
        }
    }
    catch (Exception error)
    {
        MessageBox.Show(error.Message);
    }
}

4. 额外说明

  • DataGridView会自动识别Product类的属性生成列,如果需要隐藏集合类型的列(比如features,直接显示会是System.Collections.Generic.List...),可以手动设置列的可见性:
dataGridView1.Columns["features"].Visible = false;
  • 若要展示features中的内容,可考虑使用嵌套DataGridView或自定义列模板来实现。

内容的提问来源于stack exchange,提问作者gb00-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:34:55