如何将DataTable中的数据转换为指定格式的JSON对象
实现DataTable到指定JSON格式的转换
没问题,这需求很明确,咱们可以结合.NET的LINQ和JSON序列化库来快速实现。先理清楚核心思路:先按Block字段对DataTable里的行分组,再把每组的每一行转换成{ResidentId: HouseNo}格式的对象,最后把分组结果序列化成目标JSON结构。
前置准备
如果用Json.NET(Newtonsoft.Json)这个常用的JSON库,先通过NuGet安装它:
Install-Package Newtonsoft.Json
要是你用的是.NET Core 3.0+,也可以直接用自带的System.Text.Json,不需要额外安装。
完整实现代码(Json.NET版本)
using Newtonsoft.Json; using System.Data; using System.Linq; // 初始化并填充你的DataTable(这里用示例数据) DataTable residentTable = new DataTable(); residentTable.Columns.Add("Block", typeof(string)); residentTable.Columns.Add("HouseNo", typeof(string)); residentTable.Columns.Add("ResidentId", typeof(int)); residentTable.Rows.Add("A", "101", 1); residentTable.Rows.Add("A", "102", 2); residentTable.Rows.Add("A", "103", 3); residentTable.Rows.Add("B", "101", 4); residentTable.Rows.Add("B", "102", 5); residentTable.Rows.Add("B", "104", 6); // 构造目标数据结构 var groupedResult = residentTable.AsEnumerable() .GroupBy(row => $"Block {row.Field<string>("Block")}") // 按"Block X"分组 .ToDictionary( group => group.Key, group => group.Select(row => // 把每行转换成{ResidentId: HouseNo}的字典对象 new Dictionary<int, string> { { row.Field<int>("ResidentId"), row.Field<string>("HouseNo") } } ).ToList() ); // 序列化为格式化后的JSON字符串 string targetJson = JsonConvert.SerializeObject(groupedResult, Formatting.Indented); // 输出结果(也可以直接返回或存储) Console.WriteLine(targetJson);
替代实现(System.Text.Json版本)
如果用.NET自带的JSON序列化库,只需要替换序列化部分的代码:
using System.Text.Json; // 前面的DataTable初始化和分组逻辑完全一致 string targetJson = JsonSerializer.Serialize(groupedResult, new JsonSerializerOptions { WriteIndented = true }); Console.WriteLine(targetJson);
输出结果
运行后会得到你想要的JSON格式:
{ "Block A": [ { "1": "101" }, { "2": "102" }, { "3": "103" } ], "Block B": [ { "4": "101" }, { "5": "102" }, { "6": "104" } ] }
内容的提问来源于stack exchange,提问作者Prashant Gupta
相关产品推荐
相关产品推荐

