xxxxxxxxxx
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
xxxxxxxxxx
public DataTable Read(string filePath)
{
try
{
//check if json structure is okay (http://jsonlint.com)
//generate object class http://www.jsonutils.com
DataTable dt = new DataTable();
dt = JsonConvert.DeserializeObject<DataTable>(File.ReadAllText(filePath));
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
o create a DataTable from a JSON string, you can use the Newtonsoft.Json package to deserialize the JSON string into a list of objects, and then use that list to populate the DataTable.
xxxxxxxxxx
using Newtonsoft.Json;
using System.Data;
// Define the class that matches the JSON structure
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
// Deserialize the JSON string into a list of objects
string json = @"[
{ 'Name': 'John', 'Age': 30, 'Email': 'john@example.com' },
{ 'Name': 'Jane', 'Age': 25, 'Email': 'jane@example.com' },
{ 'Name': 'Bob', 'Age': 40, 'Email': 'bob@example.com' }
]";
List<Person> people = JsonConvert.DeserializeObject<List<Person>>(json);
// Create a DataTable and populate it with the list of objects
DataTable dt = new DataTable();
foreach (var prop in typeof(Person).GetProperties())
{
dt.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (var person in people)
{
DataRow row = dt.NewRow();
foreach (var prop in typeof(Person).GetProperties())
{
row[prop.Name] = prop.GetValue(person);
}
dt.Rows.Add(row);
}
This code creates a Person class to match the JSON structure, deserializes the JSON string into a list of Person objects using JsonConvert.DeserializeObject, creates a DataTable and adds columns to match the Person class properties, and then loops through the list of Person objects to add rows to the DataTable.
xxxxxxxxxx
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Linq;
public static DataTable Tabulate(string json)
{
var jsonLinq = JObject.Parse(json);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
// Only include JValue types
if (column.Value is JValue)
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());
}