In this tutorial we create an example for json array to datatable c# using newtonsoft by the simplest method.
I created this example in C# Console Application. Also you can create this example Windows Form, WPF with DataGridView
Firstly, I am using this JSON data in my example: I created this json data and I saved it custom location
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | { "Books": [ { "title": "Broken hearts", "genre": "Romance", "price": "15" }, { "title": "Nothing in my life", "genre": "Guide", "price": "12" }, { "title": "Love for love", "genre": "Romance", "price": "6" } ] } |
In second Step: I added Newtonsoft library in my solution.
After Adding Newtonsoft library, I created DataTable, DataRow and I readed JSON data with File.ReadAllText method from custom location
1 2 3 4 5 | DataTable myTable; DataRow myNewRow; JObject result = JObject.Parse(File.ReadAllText(@"D:\books.json")); |
Reading step by step cols and rows into DataTable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | myTable = new DataTable("BookList"); myTable.Columns.Add("Title", typeof(string)); myTable.Columns.Add("Genre", typeof(string)); myTable.Columns.Add("Price", typeof(int)); // Console.WriteLine(result["Books"]); foreach (var item in result["Books"]) { myNewRow = myTable.NewRow(); myNewRow["Title"] = item["title"].ToString(); //string myNewRow["Genre"] = item["genre"].ToString(); //string myNewRow["Price"] = Convert.ToInt32(item["price"].ToString()); //integer myTable.Rows.Add(myNewRow); } |
Reading data from DataTable
1 2 3 4 5 6 | foreach (DataRow dr in myTable.Rows) { Console.WriteLine("Book : {0}\t Genre : {1} \t Price : {2} \t", dr[0], dr[1], dr[2]); } |
Here are the all codes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | DataTable myTable; DataRow myNewRow; JObject result = JObject.Parse(File.ReadAllText(@"D:\books.json")); myTable = new DataTable("BookList"); myTable.Columns.Add("Title", typeof(string)); myTable.Columns.Add("Genre", typeof(string)); myTable.Columns.Add("Price", typeof(int)); // Console.WriteLine(result["Books"]); foreach (var item in result["Books"]) { myNewRow = myTable.NewRow(); myNewRow["Title"] = item["title"].ToString(); //string myNewRow["Genre"] = item["genre"].ToString(); //string myNewRow["Price"] = Convert.ToInt32(item["price"].ToString()); //integer myTable.Rows.Add(myNewRow); } foreach (DataRow dr in myTable.Rows) { Console.WriteLine("Book : {0}\t Genre : {1} \t Price : {2} \t", dr[0], dr[1], dr[2]); } |