Convert JSON to DataTable

Viewed 319864

I have JSON in the following format:

[
    {"id":"10","name":"User","add":false,"edit":true,"authorize":true,"view":true},
    {"id":"11","name":"Group","add":true,"edit":false,"authorize":false,"view":true},
    {"id":"12","name":"Permission","add":true,"edit":true,"authorize":true,"view":true}
]

How can I convert that into a C# DataTable object as follows?

---------------------------------------------------------------------
ID    |  Name     |  Add    |   Edit  | View   | Authorize
---------------------------------------------------------------------
10    | User      | true    |  true   | true   |  true
11    | Group     | true    |  true   | true   |  true
12    | Permission| true    |  true   | true   |  true
9 Answers

Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL - an open source library

Sample below shows how to convert

string json = @"[
{""id"":""10"",""name"":""User"",""add"":false,""edit"":true,""authorize"":true,""view"":true},
{ ""id"":""11"",""name"":""Group"",""add"":true,""edit"":false,""authorize"":false,""view"":true},
{ ""id"":""12"",""name"":""Permission"",""add"":true,""edit"":true,""authorize"":true,""view"":true}
]";

using (var r = ChoJSONReader.LoadText(json))
{
    var dt = r.AsDataTable();
}

Sample fiddle: https://dotnetfiddle.net/y0siCi

json = File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\" +download_file[0]);
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

I solved it by the following - Used Pravin Pawar's answer below - for converting the JSON object to dt.

https://stackoverflow.com/a/11982180/504351

1)Send the JSON from Angular to C# controller method. 2)In C# Controller method -

convert the string data (JSON object) to a datatable.

DataTable dt = (DataTable)JsonConvert.DeserializeObject(data, (typeof(DataTable)));

3)Create a table in SQL Server database by parsing through rows and columns of the datatable dt


int dt_length = dt.Columns.Count;
            Random rand = new Random();
            string tablename = "Test" + rand.Next().ToString();
            string query = "Create table " + tablename + "  ( ";
            
            for (int i = 0; i < dt_length; i ++)
            {
                if(i == dt_length -1)
                {
                    query = query + dt.Columns[i].ColumnName + " varchar(max) ) ";
                    
                }
                else
                {
                    query = query + dt.Columns[i].ColumnName + " varchar(max), ";
                }
            }               

4)Similarly insert each of the row data in the table created. 5)This helps to dynamically create a database table from JSON.

Related