Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON to DataTable

Tags:

json

c#

datatable

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 
like image 855
Nithesh Narayanan Avatar asked Aug 16 '12 05:08

Nithesh Narayanan


People also ask

Can we convert JSON to DataTable in C#?

The JSON string will be first downloaded from an API using WebClient class and then will be converted to DataTable using JSON.Net library. Finally, the DataTable will be used to populate the GridView control in ASP.Net using C# and VB.Net.

How to Convert String to DataTable?

DT = (DataTable)JsonConvert. DeserializeObject(JSONString, (typeof(DataTable))); First, we deserialize the JSON to an object of the type data table and then convert it to a Data Table using the JsonConvert function.


2 Answers

Deserialize your jsonstring to some class

List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString); 

Write following extension method to your project

using System.ComponentModel;  public static DataTable ToDataTable<T>(this IList<T> data) {     PropertyDescriptorCollection props =     TypeDescriptor.GetProperties(typeof(T));     DataTable table = new DataTable();     for(int i = 0 ; i < props.Count ; i++)     {         PropertyDescriptor prop = props[i];         table.Columns.Add(prop.Name, prop.PropertyType);     }     object[] values = new object[props.Count];     foreach (T item in data)     {         for (int i = 0; i < values.Length; i++)         {             values[i] = props[i].GetValue(item);         }         table.Rows.Add(values);     }     return table;         } 

Call extension method like

UserList.ToDataTable<User>(); 
like image 31
Pravin Pawar Avatar answered Oct 04 '22 08:10

Pravin Pawar


There is an easier method than the other answers here, which require first deserializing into a c# class, and then turning it into a datatable.

It is possible to go directly to a datatable, with JSON.NET and code like this:

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable))); 
like image 162
Kyle Avatar answered Oct 04 '22 08:10

Kyle