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

如何将给定结构的JSON对象反序列化为DataTable

你的JSON结构里,表格列名存放在response.result.column_order数组,行数据存放在response.result.rows二维数组,每行数据的顺序和列名顺序一一对应,以下是C#环境下反序列化为DataTable的两种实现方式:

方案1:基于Newtonsoft.Json实现

这是.NET生态最常用的第三方JSON处理库,兼容性最好。

  • 先通过NuGet安装依赖包,执行命令:Install-Package Newtonsoft.Json
  • 实现代码:
using Newtonsoft.Json.Linq;
using System.Data;

// 替换为你实际的JSON字符串
string jsonInput = @"此处粘贴你的完整JSON内容";

// 解析JSON节点
JObject jsonRoot = JObject.Parse(jsonInput);
JArray colList = jsonRoot["response"]["result"]["column_order"] as JArray;
JArray rowList = jsonRoot["response"]["result"]["rows"] as JArray;

DataTable attendanceTable = new DataTable();
// 初始化表列
foreach (string colName in colList)
{
    attendanceTable.Columns.Add(colName);
}
// 逐行写入数据
foreach (JArray row in rowList)
{
    DataRow newRow = attendanceTable.NewRow();
    for (int i = 0; i < colList.Count; i++)
    {
        newRow[i] = row[i]?.ToString() ?? DBNull.Value;
    }
    attendanceTable.Rows.Add(newRow);
}
方案2:基于System.Text.Json实现

这是.NET Core 3.0、.NET 5及以上版本内置的JSON处理库,不需要额外安装第三方依赖。

  • 实现代码:
using System.Text.Json;
using System.Data;

// 替换为你实际的JSON字符串
string jsonInput = @"此处粘贴你的完整JSON内容";

// 解析JSON节点
using JsonDocument doc = JsonDocument.Parse(jsonInput);
JsonElement resultNode = doc.RootElement
    .GetProperty("response")
    .GetProperty("result");
JsonElement colList = resultNode.GetProperty("column_order");
JsonElement rowList = resultNode.GetProperty("rows");

DataTable attendanceTable = new DataTable();
// 初始化表列
foreach (JsonElement col in colList.EnumerateArray())
{
    attendanceTable.Columns.Add(col.GetString());
}
// 逐行写入数据
foreach (JsonElement row in rowList.EnumerateArray())
{
    DataRow newRow = attendanceTable.NewRow();
    int colIndex = 0;
    foreach (JsonElement cell in row.EnumerateArray())
    {
        newRow[colIndex] = cell.ValueKind == JsonValueKind.Null 
            ? DBNull.Value 
            : cell.GetString();
        colIndex++;
    }
    attendanceTable.Rows.Add(newRow);
}
扩展说明
  • 以上代码默认将所有单元格值存储为字符串类型,如果需要强类型存储(比如工时、加班时长存为数值,日期存为DateTime类型),可以在给单元格赋值时增加类型判断逻辑,对应字段调用decimal.Parse()、DateTime.Parse()等方法转换后再赋值即可。
  • 列名中包含的%特殊字符不需要额外转义,DataTable原生支持这类列名。

如果是其他语言环境(比如Python、Java),实现逻辑一致:先提取列名数组创建表结构,再遍历二维行数组逐行写入即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 03:45:33