Click here to Skip to main content
15,902,198 members
Articles
Tip/Trick
(untagged)

Convert JSON To DataTable C#

Rate me:
Please Sign up or sign in to vote.
3.50/5 (5 votes)
11 Mar 2016CPOL 60.8K   5   5
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.

C#
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);
           }
       }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
General[My vote of 1] No good sample Pin
EdWin14093-Sep-16 3:36
EdWin14093-Sep-16 3:36 
Questionjust a comment Pin
Member 1238531211-Mar-16 1:56
Member 1238531211-Mar-16 1:56 
AnswerRe: just a comment Pin
Devraj Kapdi11-Mar-16 2:01
professionalDevraj Kapdi11-Mar-16 2:01 
GeneralRe: just a comment Pin
Member 1238531211-Mar-16 2:05
Member 1238531211-Mar-16 2:05 
Smile | :) I just think that it is a bad practice to put nothing to exception block, cause ur code might work incorrectly and you won't notice that=)
GeneralRe: just a comment Pin
Devraj Kapdi11-Mar-16 2:11
professionalDevraj Kapdi11-Mar-16 2:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.