How to convert JSON to Datatable in C#

Today we will see how to convert JSON to Datatable using ASP.Net C#. JSON is easiest format to read and write. JSON stands for javascript object notation, which is an open standard for transmitting data between server and web application. JSON is a human-readable format with attribute-value pair, and it is an alternative of XML.

Below are the three ways to convert JSON to Datatable in ASP.Net C#.

Method 1: Convert JSON to Datatable in C#

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

Convert JSON to Dataset in C#
DataSet data = JsonConvert.DeserializeObject<DataSet>(json);

JSON to Datatable in ASP.Net C#

Method 2: Convert JSON to Datatable in C#

Convert complex nested JSON to Datatable c#
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Linq;

public static DataTable ConvertJsonToDatatable(string jsonString)
var jsonLinq = JObject.Parse(jsonString);

// Find the first array using Linq
var linqArray = jsonLinq.Descendants().Where(x => x is JArray).First();
var jsonArray = new JArray();

foreach (JObject row in linqArray.Children<JObject>())
var createRow = new JObject();
foreach (JProperty column in row.Properties())
// Only include JValue types
if (column.Value is JValue)
createRow.Add(column.Name, column.Value);
return JsonConvert.DeserializeObject<DataTable>(jsonArray.ToString());

Method 3: Convert JSON to Datatable in C#

//De-serialize your JSON string to your class.
List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonStr);

//Write an extension method as,
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);
return table;

//Call your extension method as,

Post a Comment