请教如何将以下的json格式转为DataTable

2024-12-29 09:20:40
推荐回答(1个)
回答1:

用正则表达式吧。public static DataTable JsonToDataTable(string strJson)
{
//取出表名
Regex rg = new Regex(@"(?<={)[^:]+(?=:/[)", RegexOptions.IgnoreCase);
string strName = rg.Match(strJson).Value;
DataTable tb = null;
//去除表名
strJson = strJson.Substring(strJson.IndexOf("[") + 1);
strJson = strJson.Substring(0, strJson.IndexOf("]"));

//获取数据
rg = new Regex(@"(?<={)[^}]+(?=})");
MatchCollection mc = rg.Matches(strJson);
for (int i = 0; i < mc.Count; i++)
{
string strRow = mc[i].Value;
string[] strRows = strRow.Split(',');

//创建表
if (tb == null)
{
tb = new DataTable();
tb.TableName = strName;
foreach (string str in strRows)
{
DataColumn dc = new DataColumn();
string[] strCell = str.Split(':');
dc.ColumnName = strCell[0].ToString();
tb.Columns.Add(dc);
}
tb.AcceptChanges();
}