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

如何将两个DataTable(单行+多行)转换为指定结构的嵌套JSON对象?

解决方案:将两个DataTable转换为指定嵌套JSON结构

针对你的需求,这里提供几种实用的实现方案,直接基于DataTable转换为目标JSON结构:

方案1:使用Newtonsoft.Json(Json.NET,推荐)

这是.NET生态中最常用的JSON序列化库,兼容性好、功能完善。

实现代码

using Newtonsoft.Json;
using System.Data;
using System.Linq;

// 处理单行统计数据dt1:转换为键值对对象
var dt1Obj = dt1.Rows.Count > 0 
    ? dt1.Columns.Cast<DataColumn>()
        .ToDictionary(col => col.ColumnName, col => dt1.Rows[0][col])
    : new Dictionary<string, object>();

// 处理多行记录数据dt2:转换为对象数组
var dt2List = dt2.AsEnumerable()
    .Select(row => dt2.Columns.Cast<DataColumn>()
        .ToDictionary(col => col.ColumnName, col => row[col]))
    .ToList();

// 包装为目标嵌套结构
var data = new { dt1 = dt1Obj, dt2 = dt2List };

// 序列化为格式化后的JSON字符串
string jsonResult = JsonConvert.SerializeObject(data, Formatting.Indented);

方案2:使用System.Text.Json(.NET Core/.NET 5+ 自带)

如果使用较新的.NET版本,推荐使用官方自带的System.Text.Json,无需额外安装包。

实现代码

using System.Text.Json;
using System.Data;
using System.Linq;

// 处理dt1
var dt1Obj = dt1.Rows.Count > 0 
    ? dt1.Columns.Cast<DataColumn>()
        .ToDictionary(col => col.ColumnName, col => dt1.Rows[0][col])
    : new Dictionary<string, object>();

// 处理dt2
var dt2List = dt2.AsEnumerable()
    .Select(row => dt2.Columns.Cast<DataColumn>()
        .ToDictionary(col => col.ColumnName, col => row[col]))
    .ToList();

// 包装结构
var data = new { dt1 = dt1Obj, dt2 = dt2List };

// 序列化(带格式化)
var serializeOptions = new JsonSerializerOptions { WriteIndented = true };
string jsonResult = JsonSerializer.Serialize(data, serializeOptions);

方案3:使用JavaScriptSerializer(兼容旧版.NET Framework)

如果项目基于.NET Framework且无法引入第三方库,可以使用这个内置序列化器,但注意它已被官方标记为过时。

实现代码

using System.Web.Script.Serialization;
using System.Data;
using System.Linq;

JavaScriptSerializer serializer = new JavaScriptSerializer();

var dt1Obj = dt1.Rows.Count > 0 
    ? dt1.Columns.Cast<DataColumn>()
        .ToDictionary(col => col.ColumnName, col => dt1.Rows[0][col])
    : new Dictionary<string, object>();

var dt2List = dt2.AsEnumerable()
    .Select(row => dt2.Columns.Cast<DataColumn>()
        .ToDictionary(col => col.ColumnName, col => row[col]))
    .ToList();

var data = new { dt1 = dt1Obj, dt2 = dt2List };
string jsonResult = serializer.Serialize(data);

说明

  • 所有方案都处理了dt1为空的情况(查询无结果时返回空对象)
  • 通过ToDictionary将DataTable的行转换为键值对结构,序列化后正好匹配你需要的JSON格式
  • 格式化后的JSON会保持示例中的缩进结构,便于阅读

内容的提问来源于stack exchange,提问作者Abdi fatah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:15:42