65.9K
CodeProject is changing. Read more.
Home

Convert JSON To DataTable C#

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (5 votes)

Mar 11, 2016

CPOL
viewsIcon

61819

Here is another way to convert JSON To DataTable with Newtonsoft.Json

Background

I have a json from text file and want to convert it into data table in C#. Here, I used dynamic object to get Deserialize Object from Newtonsoft.Json and processed accordingly to convert it into DataTable.

Using the Code

The json.txt contains:

{"offers":[{"rule_id":"3","name":"B2G1",
"description":null},{"rule_id":"5",
"name":"Free Delivery for Orders above Rs 599",
"description":null}],"coupons":[{"rule_id":"1",
"name":" 5% off ","description":" 5% off ",
"coupon_code":"COUPON5"},{"rule_id":"2",
"name":"50% Discount","description":null,
"coupon_code":"pradeep"},{"rule_id":"4",
"name":"50% off","description":null,
"coupon_code":"123456"}]}

Refer --> http://www.jsoneditoronline.org/# to validate json

Download --> Newtonsoft.Json.dll

Use the below method to convert JSON into DataTable.

 private void ConvertJsonToDataTable()
        {
            try
            {
                string jsonString = File.ReadAllText("E:\\json.txt");

                if (!String.IsNullOrWhiteSpace(jsonString))
                {
                    dynamic dynObj = JsonConvert.DeserializeObject(jsonString);
                    var sOffers = dynObj.offers;
                    var sCoupons = dynObj.coupons;

                    DataTable dtPromotions = new DataTable();
                    dtPromotions.Columns.Add("rule_id", typeof(string));
                    dtPromotions.Columns.Add("name", typeof(string));
                    dtPromotions.Columns.Add("coupon_code", typeof(string));
                    dtPromotions.Columns.Add("description", typeof(string));

                    foreach (var cou in sCoupons)
                    {
                        string cou1 = Convert.ToString(cou);
                        string[] RowData = Regex.Split(cou1.Replace
                        ("{", "").Replace("}", ""), ",");
                        DataRow nr = dtPromotions.NewRow();
                        foreach (string rowData in RowData)
                        {
                            try
                            {
                                int idx = rowData.IndexOf(":");
                                string RowColumns = rowData.Substring
                                (0, idx - 1).Replace("\"", "").Trim();
                                string RowDataString = rowData.Substring
                                (idx + 1).Replace("\"", "");
                                nr[RowColumns] = RowDataString;
                            }
                            catch (Exception ex)
                            {
                                continue;
                            }
                        }
                        dtPromotions.Rows.Add(nr);
                    }

                    foreach (var off in sOffers)
                    {
                        string off1 = Convert.ToString(off);
                        string[] RowData = Regex.Split(off1.Replace
                        ("{", "").Replace("}", ""), ",");
                        DataRow nr = dtPromotions.NewRow();
                        foreach (string rowData in RowData)
                        {
                            try
                            {
                                int idx = rowData.IndexOf(":");
                                string RowColumns = rowData.Substring
                                (0, idx - 1).Replace("\"", "").Trim();
                                string RowDataString = rowData.Substring
                                (idx + 1).Replace("\"", "");
                                nr[RowColumns] = RowDataString;
                            }
                            catch (Exception ex)
                            {
                                continue;
                            }
                        }
                        dtPromotions.Rows.Add(nr);
                    }

                    if (dtPromotions.Rows.Count > 0)
                    {
                        dgvPromotions.DataSource = dtPromotions;
                        dgvPromotions.Columns["rule_id"].Visible = false;
                        dgvPromotions.Columns["name"].HeaderText = "Name";
                        dgvPromotions.Columns["coupon_code"].HeaderText = "Coupon Code";
                        dgvPromotions.Columns["description"].HeaderText = "Description";
                        dgvPromotions.ClearSelection();
                    }
                }
            }
            catch (Exception ex)
            {
                    MessageBox.Show(ex.Message, "ERROR", 
			MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }