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
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.
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.
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>();
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With