C implements a method to convert json to DataTable
- 2020-12-20 03:43:26
- OfStack
This article shows an example of how C# implements the transformation from json to DataTable. Share to everybody for everybody reference. Specific implementation methods are as follows:
#region will json convert DataTable
/// <summary>
/// will json convert DataTable
/// </summary>
/// <param name="strJson"> To get the json</param>
/// <returns></returns>
private DataTable JsonToDataTable(string strJson)
{
// conversion json format
strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
// Take out the name of the table
var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
string strName = rg.Match(strJson).Value;
DataTable tb = null;
// Remove the name of the table
strJson = strJson.Substring(strJson.IndexOf("[") + 1);
strJson = strJson.Substring(0, strJson.IndexOf("]"));
// To get the data
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('*');
// Create a 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();
}
// Increase the content of
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
Hopefully this article has helped you with your C# programming.