首页 > 代码库 > C# json字符串转DataTable
C# json字符串转DataTable
我的json格式是这样的:
{"success":true,"data":[{"C4":"英语","C3":"","C1":"99","C2":"CCC"},{"C4":"数学","C3":"","C1":"55","C2":"DDD"}]}
转出来的结果:
代码:
1. 需要引用 Newtonsoft.Json.dll , 可以去网上下载
2.引入System.Web.Extensions 组件
引用 :
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
3.
public DataTable JsonToDataTable(string strJson) { DataTable dt =null ; try { JObject jo = (JObject)JsonConvert.DeserializeObject(strJson); bool success = (bool)jo["success"]; if (!success) { return null; } JArray ja = (JArray)jo["data"]; dt = ToDataTable(ja.ToString()); } catch (Exception ex) { return null; } return dt; }
方法ToDataTable
public DataTable ToDataTable( string json) { DataTable dataTable = new DataTable(); //实例化 DataTable result; JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值 ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json); if (arrayList.Count > 0) { foreach (Dictionary<string, object> dictionary in arrayList) { //if (dictionary.Keys.Count<string>() == 0) if (dictionary.Keys.Count == 0) { result = dataTable; return result; } if (dataTable.Columns.Count == 0) { foreach (string current in dictionary.Keys) { dataTable.Columns.Add(current, dictionary[current].GetType()); } } DataRow dataRow = dataTable.NewRow(); foreach (string current in dictionary.Keys) { dataRow[current] = dictionary[current]; } dataTable.Rows.Add(dataRow); } } result = dataTable; return result; }
C# json字符串转DataTable
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。