Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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 human readable format with attribute-value pair, and it is 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(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())
{
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);
}
}
jsonArray.Add(createRow);
}
return JsonConvert.DeserializeObject(jsonArray.ToString());
}


Method 3: Convert JSON to Datatable in C#

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

//Write an extension method as,
public static DataTable ToDataTable(this IList data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();

for(int i = 0 ; 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[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}

//Call your extension method as,
users.ToDataTable();


This post first appeared on Ask For Program, please read the originial post: here

Share the post

How to convert JSON to Datatable in C#

×

Subscribe to Ask For Program

Get updates delivered right to your inbox!

Thank you for your subscription

×