Top Ad unit 728 × 90

New Articles

random

Converting Data Table to Json Format in C#



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.

How to convert datatable to json object in C# ?

In the following example I will show 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 :-
C# Source Code -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
There is another way to convert datatable to json format using Serialization in asp.net. Find the following source code below and find the way about DataTable JSON Serialization in ASP.Net:- [post_ad]
C# Source Code -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
I hope you will enjoy the development tip while programming with C# in ASP.Net application. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome. 

Also If you like this article, don't forget to share this article with your friends and colleagues.
Converting Data Table to Json Format in C# Reviewed by Ravi Kumar on 4:03 PM Rating: 5

5 comments:

  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

All Rights Reserved by eTechpulse © 2014 - 2015
Powered By Blogger

Contact Form

Name

Email *

Message *

Powered by Blogger.