Wednesday 20 September 2017

Convert JSON String to DataTable in ASP.Net

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Text.RegularExpressions;

  5. public class ConvertJsonStringToDataTable
  6. {
  7.    public DataTable JsonStringToDataTable(string jsonString)
  8.    {
  9.       DataTable dt = new DataTable();
  10.       string[] jsonStringArray = Regex.Split(jsonString.Replace("[""").Replace("]",""), "},{");
  11.       List<string> ColumnsName = new List<string>();
  12.       foreach (string jSA in jsonStringArray)
  13.       {
  14.          string[] jsonStringData = Regex.Split(jSA.Replace("{""").Replace("}"""),",");
  15.          foreach (string ColumnsNameData in jsonStringData)
  16.          {
  17.             try
  18.             {
  19.                int idx = ColumnsNameData.IndexOf(":");
  20.                string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"""");
  21.                if (!ColumnsName.Contains(ColumnsNameString))
  22.                {
  23.                   ColumnsName.Add(ColumnsNameString);
  24.                }
  25.             }
  26.             catch (Exception ex)
  27.             {
  28.                throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
  29.             }
  30.          }
  31.          break;
  32.       }
  33.       foreach (string AddColumnName in ColumnsName)
  34.       {
  35.          dt.Columns.Add(AddColumnName);
  36.       }
  37.       foreach (string jSA in jsonStringArray)
  38.       {
  39.          string[] RowData = Regex.Split(jSA.Replace("{""").Replace("}"""), ",");
  40.          DataRow nr = dt.NewRow();
  41.          foreach (string rowData in RowData)
  42.          {
  43.             try
  44.             {
  45.                int idx = rowData.IndexOf(":");
  46.                string RowColumns = rowData.Substring(0, idx - 1).Replace("\"""");
  47.                string RowDataString = rowData.Substring(idx + 1).Replace("\"""");
  48.                nr[RowColumns] = RowDataString;
  49.             }
  50.             catch (Exception ex)
  51.             {
  52.                continue;
  53.             }
  54.          }
  55.          dt.Rows.Add(nr);
  56.       }
  57.       return dt;
  58.    }
  59. }


No comments:

Post a Comment