Convert JSON to DataTable

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)));

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>();

Tags:

C#

Datatable

Json