C# | 使用DataGridView展示JSON数组

在这里插入图片描述

C# | 使用DataGridView展示JSON数组

前言

你想展示一个复杂的JSON数组数据吗?但是你却不知道该如何展示它,是吗?没问题,因为本文就是为解决这个问题而生的!使用DataGridView轻松地将JSON数组数据以表格的形式呈现出来,这样你就可以更加清晰地了解和处理数据了。

让我们一起来探索如何实现吧!


实现原理

  1. 定义一个 JSON 格式的字符串。
  2. 使用 Newtonsoft.Json 库的 JsonConvert.DeserializeObject 方法将 JSON 反序列化为 List<Dictionary<string, object>> 对象列表。
  3. 遍历对象列表,将每个对象的属性作为 DataGridView 中的一列,并将对象的属性值作为 DataGridView 中的一行。
  4. 将 DataGridView 显示在 UI 界面上。

实现过程

第一步,清空 DataGridView 中的所有列和行。

dataGridView1.Columns.Clear();
dataGridView1.Rows.Clear();

第二步,使用 Newtonsoft.Json 库的 JsonConvert.DeserializeObject 方法将 JSON 反序列化为 List<Dictionary<string, object>> 对象列表。

string json = "[{ \"Name\": \"Alice\", \"Age\": 23 }, { \"Name\": \"Bob\", \"Age\": 25 }, { \"Name\": \"Charlie\", \"Age\": 27 }]";
List<Dictionary<string, object>> data = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);

第三步,遍历对象列表,将每个对象的属性作为 DataGridView 中的一列。

foreach (var row in data)
{
    
    
    foreach (var column in row)
    {
    
    
        // 如果列不存在,添加列
        if (!dataGridView1.Columns.Contains(column.Key))
        {
    
    
            dataGridView1.Columns.Add(column.Key, column.Key);
        }
    }
}

第四步,遍历对象列表,将对象的属性值作为 DataGridView 中的一行。

foreach (var row in data)
{
    
    
    int rowIndex = dataGridView1.Rows.Add();
    foreach (var column in row)
    {
    
    
        dataGridView1.Rows[rowIndex].Cells[column.Key].Value = column.Value;
    }
}

完整源码

using Newtonsoft.Json;

// 清空 DataGridView 中的所有列和行
dataGridView1.Columns.Clear();
dataGridView1.Rows.Clear();

// JSON 格式的字符串
string json = "[{ \"Name\": \"Alice\", \"Age\": 23 }, { \"Name\": \"Bob\", \"Age\": 25 }, { \"Name\": \"Charlie\", \"Age\": 27 }]";

// 将 JSON 反序列化为对象列表
List<Dictionary<string, object>> data = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);

// 遍历对象列表,将每个对象的属性作为 DataGridView 中的一列
foreach (var row in data)
{
    
    
    foreach (var column in row)
    {
    
    
        // 如果列不存在,添加列
        if (!dataGridView1.Columns.Contains(column.Key))
        {
    
    
            dataGridView1.Columns.Add(column.Key, column.Key);
        }
    }
}

// 遍历对象列表,将对象的属性值作为 DataGridView 中的一行
foreach (var row in data)
{
    
    
    int rowIndex = dataGridView1.Rows.Add();
    foreach (var column in row)
    {
    
    
        dataGridView1.Rows[rowIndex].Cells[column.Key].Value = column.Value;
    }
}

每次运行代码时,DataGridView 都会动态生成列。

猜你喜欢

转载自blog.csdn.net/lgj123xj/article/details/129942959