Hi
I have the following sample JSON where i want to split it and copy to 2 different datatables like
ID,Name & Description to one table and Distributors data to another table Kindly help me with this
JSON
[
{
"Id":"123",
"Name":"abc",
"Description":"abc company",
"Distributors":[
{
"DName":"joe",
"LastName":"BIDEN",
"Email":"[email protected]"
},
{
"DName":"Donald",
"LastName":"TRUMP",
"Email":"[email protected]"
}
]
}
]
Amit MohantyRank #112 · 20K reputationPosted Jan 31, 2024, 5:50 AM EST
Check this by using Newtonsoft.Json library.
var jsonData = JsonConvert.DeserializeObject(your_json_data); // Create DataTable for ID, Name, and Description DataTable mainTable = new DataTable(); mainTable.Columns.Add("ID"); mainTable.Columns.Add("Name"); mainTable.Columns.Add("Description"); // Create DataTable for Distributors DataTable distributorTable = new DataTable(); distributorTable.Columns.Add("ID"); distributorTable.Columns.Add("DName"); distributorTable.Columns.Add("LastName"); distributorTable.Columns.Add("Email"); foreach (var item in jsonData) { DataRow mainRow = mainTable.NewRow(); mainRow["ID"] = item["Id"].ToString(); mainRow["Name"] = item["Name"].ToString(); mainRow["Description"] = item["Description"].ToString(); mainTable.Rows.Add(mainRow); foreach (var distributor in item["Distributors"]) { DataRow distributorRow = distributorTable.NewRow(); distributorRow["ID"] = item["Id"].ToString(); distributorRow["DName"] = distributor["DName"].ToString(); distributorRow["LastName"] = distributor["LastName"].ToString(); distributorRow["Email"] = distributor["Email"].ToString(); distributorTable.Rows.Add(distributorRow); } } Console.WriteLine("Main Table:"); foreach (DataRow row in mainTable.Rows) { Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Description"]}"); } Console.WriteLine("\nDistributor Table:"); foreach (DataRow row in distributorTable.Rows) { Console.WriteLine($"{row["ID"]}, {row["DName"]}, {row["LastName"]}, {row["Email"]}"); }Meghana9 reputationPosted Jan 31, 2024, 7:21 AM EST
Thank You very much Amit. It worked
Sam HobbsRank #107 · 20.5K reputationPosted Feb 1, 2024, 10:45 AM EST
Prior to .Net Core Newtonsoft was the best choice but the
System.Text.JsonandSystem.Text.Json.Serializationnamespaces are new for .Net Core. If you are using or can use .Net Core then the namespaces provided by .Net Core are likely easier.Tuhin PaulRank #7 · 71.9K reputationPosted Feb 1, 2024, 12:47 PM EST
I have few refactor pointers worth to mention based on the accepted answer:
1. Explicitly specify data types for columns to improve performance and memory usage.
2. Use StringBuilder for efficient string concatenation, especially for larger datasets.
3. Combine loops and use column-based assignment for readability and potential performance gains.
4. Using dynamic or creating strongly typed classes for better JSON data handling, depending on your usage.