Json stands for Java Script Object Notation. It is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. Read more


How to convert datatable to json object in C# ?

In this article I will share how to convert c# datatable to json schema in different ways. Lets start with the customize way to convert data table to json array. Follow the c# code below :-

Example 1
public static string ConvertTableToJSON()
    {
        DataTable dtEmployee = new DataTable(); 
       
        dtEmployee.Columns.Add("EmpId", typeof(int));
        dtEmployee.Columns.Add("Name", typeof(string));
        dtEmployee.Columns.Add("Address", typeof(string));
        dtEmployee.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
        dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
        dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
        dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
        dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);

        string[] jsonArray = new string[dtEmployee.Columns.Count];
        string headString = string.Empty;

        for (int i = 0; i < dtEmployee.Columns.Count; i++)
        {
            jsonArray[i] = dtEmployee.Columns[i].Caption; // Array for all columns
            headString += "'" + jsonArray[i] + "' : '" + jsonArray[i] + i.ToString() + "%" + "',";
        }

        headString = headString.Substring(0, headString.Length - 1);
       
        StringBuilder sb = new StringBuilder();
        sb.Append("[");

        if (dtEmployee.Rows.Count > 0)
        {
            for (int i = 0; i < dtEmployee.Rows.Count; i++)
            {
                string tempString = headString;
                sb.Append("{");

                // To get each value from the datatable
                for (int j = 0; j < dtEmployee.Columns.Count; j++)
                {
                    tempString = tempString.Replace(dtEmployee.Columns[j] + j.ToString() + "%", dtEmployee.Rows[i][j].ToString());
                }

                sb.Append(tempString + "},");
            }
        }
        else
        {
            string tempString = headString;
            sb.Append("{");
            for (int j = 0; j < dtEmployee.Columns.Count; j++)
            {
                tempString = tempString.Replace(dtEmployee.Columns[j] + j.ToString() + "%", "-");
            }

            sb.Append(tempString + "},");
        }

        sb = new StringBuilder(sb.ToString().Substring(0, sb.ToString().Length - 1));
        sb.Append("]");       
        return sb.ToString(); // json formated output
    }

converting, data table, c# datatable, json, json schema,json example,json format, json object
Json Example 1 Output
Now there is another way to convert datatable to json format using Serialization in asp.net as well. Find the c# code below :-

Example 2
public string GetJsonString()
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row = null;

        DataTable dtEmployee = new DataTable();

        dtEmployee.Columns.Add("EmpId", typeof(int));
        dtEmployee.Columns.Add("Name", typeof(string));
        dtEmployee.Columns.Add("Address", typeof(string));
        dtEmployee.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
        dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
        dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
        dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
        dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);

        foreach (DataRow dr in dtEmployee.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dtEmployee.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
        return serializer.Serialize(rows);
    }    

converting, data table, c# datatable, json, json schema,json example,json format, json object,json array, serialziation, asp.net
Json Example 2 Output
 Download the source code click here

Conclusion : It was fun in learning and writing an article on Converting Data Table to Json. I hope this article will be helpful for enthusiastic peoples who are eager to learn and implement some interesting stuffs in new technology. 
Please feel free to comment your opinion about this article or whatever you feel like telling me. Also if you like this article, don't forget to share this article with your friends. Thanks!

Post a Comment

  1. This is the best way to serialize in JSON format. Thanks a lot.

    ReplyDelete
  2. Replies
    1. u're welcome.. :) and keep visiting for more articles.

      Delete
  3. Replies
    1. u're welcome.. :) and keep visiting for more articles.

      Delete

 
Top