C#Json转DataTable
需求:有一个log文件,需要整理成Excel,日志文件里面的数据都是json字符串
思路是,把Json字符串转换成DataTable,然后导出到Excel
在网上找了一些资料,整理了以下三种类型的Json
一、Json转换DataTable
1.处理简单Json:
[{"mac":"20:f1:7c:c5:cd:80","rssi":"-86","ch":""},{"mac":"20:f1:7c:c5:cd:85","rssi":"-91","ch":""}]
/// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static DataTable ToDataTableTwo(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > )
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == )
{
result = dataTable;
return result;
}
//Columns
if (dataTable.Columns.Count == )
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
//Rows
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
}
dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
}
}
}
catch
{
}
result = dataTable;
return result;
}
2.处理复杂Json
[{"id":"00e58d51","data":[{"mac":"20:f1:7c:c5:cd:80","rssi":"-86","ch":""},{"mac":"20:f1:7c:c5:cd:85","rssi":"-91","ch":""}]},
{"id":"00e58d53","data":[{"mac":"bc:d1:77:8e:26:78","rssi":"-94","ch":""},{"mac":"14:d1:1f:3e:bb:ac","rssi":"-76","ch":""},{"mac":"20:f1:7c:d4:05:41","rssi":"-86","ch":""}]}]
/// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static DataTable ToDataTable(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > )
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == )
{
result = dataTable;
return result;
}
//Columns
if (dataTable.Columns.Count == )
{
foreach (string current in dictionary.Keys)
{
if (current != "data")
dataTable.Columns.Add(current, dictionary[current].GetType());
else
{
ArrayList list = dictionary[current] as ArrayList;
foreach (Dictionary<string, object> dic in list)
{
foreach (string key in dic.Keys)
{
dataTable.Columns.Add(key, dic[key].GetType());
}
break;
}
}
}
}
//Rows
string root = "";
foreach (string current in dictionary.Keys)
{
if (current != "data")
root = current;
else
{
ArrayList list = dictionary[current] as ArrayList;
foreach (Dictionary<string, object> dic in list)
{
DataRow dataRow = dataTable.NewRow();
dataRow[root] = dictionary[root];
foreach (string key in dic.Keys)
{
dataRow[key] = dic[key];
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
}
catch
{
}
result = dataTable;
return result;
}
3.处理不规则Json,因为列并不确定,所以直接定义列,不动态生成
[{"id":"00e58d53","data":[{"mac":"34:b3:54:89:86:64","rssi":"-86","ch":""},{"mac":"50:bd:5f:02:80:44","rssi":"-90","ch":""}]},
{"id":"00ccda81","data":[{"mac":"bc:46:99:4e:96:c8","rssi":"-92","ch":""},{"mac":"bc:3a:ea:fc:77:6c","rssi":"-93","ch":"","ds":"Y","essid":"vienna hotel WIFI"}]}]
/// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static DataTable ToDataTable(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
dataTable.Columns.Add("id");
dataTable.Columns.Add("mac");
dataTable.Columns.Add("rssi");
dataTable.Columns.Add("ch");
dataTable.Columns.Add("ts");
dataTable.Columns.Add("tmc");
dataTable.Columns.Add("tc");
dataTable.Columns.Add("ds");
dataTable.Columns.Add("essid");
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > )
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == )
{
result = dataTable;
return result;
}//Rows
string root = "";
foreach (string current in dictionary.Keys)
{
if (current != "data")
root = current;
else
{
ArrayList list = dictionary[current] as ArrayList;
foreach (Dictionary<string, object> dic in list)
{
DataRow dataRow = dataTable.NewRow();
dataRow[root] = dictionary[root];
foreach (string key in dic.Keys)
{
dataRow[key] = dic[key];
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
}
catch
{
}
result = dataTable;
return result;
}
二、导出Excel
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="table"></param>
/// <param name="file"></param>
public void dataTableToCsv(DataTable table, string file)
{
string title = "";
FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
for (int i = ; i < table.Columns.Count; i++)
{
title += table.Columns[i].ColumnName + "\t"; //栏位:自动跳到下一单元格
}
title = title.Substring(, title.Length - ) + "\n";
sw.Write(title);
foreach (DataRow row in table.Rows)
{
string line = "";
for (int i = ; i < table.Columns.Count; i++)
{
line += row[i].ToString().Trim() + "\t"; //内容:自动跳到下一单元格
}
line = line.Substring(, line.Length - ) + "\n";
sw.Write(line);
}
sw.Close();
fs.Close();
}
三、调用实现,数据导出到Excel
protected void Button1_Click(object sender, EventArgs e)
{
string str = File.ReadAllText(@"C:\Users\Admin\Desktop\json.txt");
DataTable dt = ToDataTable(str);
this.dataTableToCsv(dt, @"E:\json.xls"); //调用函数
}
C#Json转DataTable的更多相关文章
- #region Json转DataTable
#region Json转DataTable private DataTable Json2Dtb(string json) { JavaScrip ...
- DateTable与List<T>相互转换 及JSON与DataTable(DataSet)相互转化
http://www.360doc.com/content/13/0712/09/10504424_299336674.shtml Linq处理List数据 http://blog.163.com/l ...
- json转datatable(正则表达式的方法)
/// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson" ...
- DataTable转Json,Json转DataTable
// 页面加载时 /// </summary> /// <param name="sender"></param> /// <param ...
- c# 将json转换为DataTable
/// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson" ...
- json与DataTable相互转换
首先我们看看 Newtonsoft.Json.JsonConvert 是怎么完成的: DataTable table = new DataTable(); table.Columns.Add(&quo ...
- PCB MS SQL 存储过程(CLR) 实现Json转DataTable表的方法
一.准备需转为DataTable的json字符串 原json字符串数据 [{"TechName":"ECN","TechNo":" ...
- c#常用的Datable转换为json,以及json转换为DataTable操作方法
#region DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...
- JSON与DataTable(DataSet)相互转化
public static string CreateJsonParameters(DataTable dt) { /* /******************** ...
随机推荐
- 题目1010:A + B
题目描述: 读入两个小于100的正整数A和B,计算A+B. 需要注意的是:A和B的每一位数字由对应的英文单词给出. 输入: 测试输入包含若干测试用例,每个测试用例占一行,格式为"A + B ...
- Python创建容器和集合之源码分析
_collections_abc.py文件中提供了许多抽象基类,这些类将集合分解成许多互相独立的属性集 __all__ = ["Awaitable", "Coroutin ...
- IPFS家族(二)
go-ipfs IPFS协议的go语言实现,ipfs的核心协议,最新版是v0.4.13 下载地址:https://dist.ipfs.io/#go-ipfs 源代码地址:https://github. ...
- 简单了解C语言内嵌汇编
最近看自旋锁的实现,自选锁的循环查找锁的主要实现类似如下,该实现使用到了内嵌的汇编(摘自sanos内核,源代码有2处实现,一处使用intel汇编,是没有问题的,另一处使用内嵌汇编语法,源代码中为cmp ...
- Proxy和Reflect
原因 最近在写 unar.js(一个技术超越react angular vue)的mvvm库.通过研究proxy的可行性.故作以下研究 Proxy代理一个函数 var fn=function(){ c ...
- 笔记:MyBatis 动态SQL
有时候,静态的SQL语句并不能满足应用程序的需求.我们可以根据一些条件,来动态地构建SQL语句.例如,在Web应用程序中,有可能有一些搜索界面,需要输入一个或多个选项,然后根据这些已选择的条件去执行检 ...
- 【Python】 汉字转化汉语拼音pinyin
pinyin pinyin模块是github上一个小项目,在github.com/cleverdeng/pinyin.py上面可以下到源码.衷心感谢那些为这个模块做出贡献的人来方便我们[鞠躬] 安装: ...
- PLSQL配置怎么连ORACLE
如果是windows的话,在服务里面就可以查服务要启动,监听也要启动!可以用lsnrctl命令查看监听! 首先你需要在我的电脑的属性里,找到环境变量,配置系统下面的path,看看里面指向的是哪里(我的 ...
- java中的notify和notifyAll有什么区别?
先说两个概念:锁池和等待池 锁池:假设线程A已经拥有了某个对象(注意:不是类)的锁,而其它的线程想要调用这个对象的某个synchronized方法(或者synchronized块),由于这些线程在进入 ...
- 对于分支界限法的理解(补出门门票-week13,结对伙伴对我提的问题的答案)
首先我的结对伙伴给我提出了一个这样的问题: 使用分支界限法求解"背包问题"的步骤. 当时我是这样回答他的: ub=v+(W-w)x(v(i+1)/w(i+1)) 这个问题我在课上也 ...