C#实现将json转换为DataTable的方法
程序员文章站
2024-02-11 08:23:16
本文实例讲述了c#实现将json转换为datatable的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:#region 将json转换为datata...
本文实例讲述了c#实现将json转换为datatable的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
#region 将json转换为datatable
/// <summary>
/// 将json转换为datatable
/// </summary>
/// <param name="strjson">得到的json</param>
/// <returns></returns>
private datatable jsontodatatable(string strjson)
{
//转换json格式
strjson = strjson.replace(",\"", "*\"").replace("\":", "\"#").tostring();
//取出表名
var 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)
{
var dc = new datacolumn();
string[] strcell = str.split('#');
if (strcell[0].substring(0, 1) == "\"")
{
int a = strcell[0].length;
dc.columnname = strcell[0].substring(1, a - 2);
}
else
{
dc.columnname = strcell[0];
}
tb.columns.add(dc);
}
tb.acceptchanges();
}
//增加内容
datarow dr = tb.newrow();
for (int r = 0; r < strrows.length; r++)
{
dr[r] = strrows[r].split('#')[1].trim().replace(",", ",").replace(":", ":").replace("\"", "");
}
tb.rows.add(dr);
tb.acceptchanges();
}
return tb;
}
#endregion
/// <summary>
/// 将json转换为datatable
/// </summary>
/// <param name="strjson">得到的json</param>
/// <returns></returns>
private datatable jsontodatatable(string strjson)
{
//转换json格式
strjson = strjson.replace(",\"", "*\"").replace("\":", "\"#").tostring();
//取出表名
var 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)
{
var dc = new datacolumn();
string[] strcell = str.split('#');
if (strcell[0].substring(0, 1) == "\"")
{
int a = strcell[0].length;
dc.columnname = strcell[0].substring(1, a - 2);
}
else
{
dc.columnname = strcell[0];
}
tb.columns.add(dc);
}
tb.acceptchanges();
}
//增加内容
datarow dr = tb.newrow();
for (int r = 0; r < strrows.length; r++)
{
dr[r] = strrows[r].split('#')[1].trim().replace(",", ",").replace(":", ":").replace("\"", "");
}
tb.rows.add(dr);
tb.acceptchanges();
}
return tb;
}
#endregion
希望本文所述对大家的c#程序设计有所帮助。
上一篇: java数字转汉字工具类详解