/*====================Convert json to DataTable========================== ========*/ //Convert json format strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString(); // get the table name var rg = new System.Text.RegularExpressions.Regex(@"(?<={)[^:]+(?=:\[)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); string strName = rg.Match(strJson).Value; DataTable tb = null; // remove table name strJson = strJson.Substring(strJson.IndexOf("[") + 1); strJson = strJson.Substring(0, strJson.IndexOf("]")); //retrieve data rg = new System.Text.RegularExpressions.Regex(@"(?<={)[^}]+(?=})"); System.Text.RegularExpressions.MatchCollection mc = rg.Matches(strJson); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split('*'); //create table 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(); } //add content 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(); }
Convert list and json to DataTable
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326188723&siteId=291194637
Ranking