C# Json转DataTable
开发语言 C#
开发环境 .net framework 4.7.2
Newtonsoft.Json 版本 6.0
准备好Json数据,Json数据如下:
{"columns":["列1","列2"],"rows":{"0":{"列1":"1","列2":"2"},"2":{"列1":"11","列2":"22"}}}
Json格式化效果如下:
下面是服务器端代码,方法可以直接复制
1 /// <summary> 2 /// 根据传入的JSON数据,生成表格 3 /// </summary> 4 /// <param name="FiledsNames">列集合</param> 5 /// <param name="Rows">行集合</param> 6 /// <returns></returns> 7 public static DataTable GetDataTableByJson(JToken FiledsNames, JToken Rows) 8 { 9 DataTable result = new DataTable(); 10 //增加列 11 foreach (JToken i in FiledsNames) 12 { 13 DataColumn tempColumn = new DataColumn(); 14 tempColumn.ColumnName = i.ToString(); 15 tempColumn.DataType = i.GetType(); 16 result.Columns.Add(tempColumn); 17 } 18 19 //增加行 20 foreach (JToken i in Rows) 21 { 22 foreach (JToken l in i) 23 { 24 DataRow tempRow = result.NewRow(); 25 List<object> rowsList = new List<object>(); 26 foreach (JToken z2 in FiledsNames) 27 { 28 JToken tempRowValue = l[z2.ToString()]; 29 rowsList.Add(tempRowValue); 30 } 31 tempRow.ItemArray = rowsList.ToArray(); 32 result.Rows.Add(tempRow); 33 } 34 } 35 return result; 36 }