;

How to Convert DataTable to JSON Format in C#


Tutorialsrack 24/11/2019 C#

In this article, we will learn how to convert DataTable to JSON Format in C#. In Other Words, we can say how to serialize a DataTable to a JSON Format in C#. 

So there are three ways to do this conversion from DataTable to a JSON Format are as follow:

  1. By Using Newtonsoft.Json DLL
  2. By Using JavaScriptSerializer
  3. By Using StringBuilder

Using any one of the methods will convert the DataTable to JSON Format in C#.

Here, we add dynamic rows to DataTable for using in this example for converting DataTable to JSON Format or we can use our database to fetch the record and bind into the Datatable. But here we add dynamic rows to our DataTable using the method given below:

Example - Here we add dynamic rows to our DataTable using this method
public static DataTable getData()
 {
        DataTable dt = new DataTable();
        dt.Columns.Add("Id", typeof(Int32));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Designation", typeof(string));
        dt.Columns.Add("Location", typeof(string));
        dt.Rows.Add(1, "Sourabh Chauhan", "Software Developer", "Delhi");
        dt.Rows.Add(2, "Amit Mishra", "UX Designer", "Mumbai");
        dt.Rows.Add(3, "John Doe", "Project Manager", "Scottland");
        dt.Rows.Add(4, "Tommy Brown", "Electrician", "Sydney");
        dt.Rows.Add(5, "Vaibhav Sharma", "Network Engineer", "New Delhi");
        dt.Rows.Add(6, "Sankalp Sharma", "Accountant", "New York");
        dt.Rows.Add(7, "Raju Chauhan", "Mechanic", "Mumbai");
        dt.Rows.Add(8, "Jaden White", "Electrician", "Paris");
        dt.Rows.Add(9, "Raghav Yadav", "Web Designer", "Noida");
        dt.Rows.Add(10, "Dinesh Verma", "Team Leader", "Delhi");
        return dt;
}

Method 1: Convert DataTable To JSON Format By Using Newtonsoft.Json in C#

In this method, first, we need to download Newtonsoft.Json DLL from Nuget.org.

Here is the code to convert DataTable To Json Format in C#.

Example - Convert DataTable To JSON Format By Using Newtonsoft.Json in C#
using Newtonsoft.Json;
using System;
using System.Data;

namespace Tutorialsrack
{
    class Program
    {
        /* Convert DataTable to JSON Format using JSON.NET in C# */
        static void Main(string[] args)
        {
            Console.WriteLine("--Convert DataTable To JSON Format using JSON.NET--");
            string JsonString2 = Convert_DataTableToJSON_With_JSONNet(getData());
            Console.WriteLine(JsonString2);

            Console.ReadKey();
        }

        public static DataTable getData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(Int32));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Designation", typeof(string));
            dt.Columns.Add("Location", typeof(string));
            dt.Rows.Add(1, "Sourabh Chauhan", "Software Developer", "Delhi");
            dt.Rows.Add(2, "Amit Mishra", "UX Designer", "Mumbai");
            dt.Rows.Add(3, "John Doe", "Project Manager", "Scottland");
            dt.Rows.Add(4, "Tommy Brown", "Electrician", "Sydney");
            dt.Rows.Add(5, "Vaibhav Sharma", "Network Engineer", "New Delhi");
            dt.Rows.Add(6, "Sankalp Sharma", "Accountant", "New York");
            dt.Rows.Add(7, "Raju Chauhan", "Mechanic", "Mumbai");
            dt.Rows.Add(8, "Jaden White", "Electrician", "Paris");
            dt.Rows.Add(9, "Raghav Yadav", "Web Designer", "Noida");
            dt.Rows.Add(10, "Dinesh Verma", "Team Leader", "Delhi");
            return dt;
        }
        public static string Convert_DataTableToJSON_With_JSONNet(DataTable table)
        {
            string JSONString = string.Empty;
            JSONString = JsonConvert.SerializeObject(table);
            return JSONString;
        }
       
    }
}

Method 2:  Convert DataTable To JSON Format By Using JavaScriptSerializer Class  in C#

In this method, we use JavaScriptSerializer class which is used for serializing objects into JSON format and deserialize it back to objects and this class belongs to the System.Web.Script.Serialization namespace. First, we need to do is import the System.Web.Script.Serialization namespace.

Here is the code to convert DataTable To Json Format using JavaScriptSerializer class in C#.

Example - Convert DataTable To JSON Format By Using JavaScriptSerializer Class  in C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;

namespace Tutorialsrack
{
    class Program
    {
        /* Convert DataTable to JSON Format using JavaScriptSerializer class in C# */
        static void Main(string[] args)
        {
            Console.WriteLine("--Convert DataTable To JSON Format using JavaScriptSerializer--");
            string JsonString2 = COnvert_DataTableToJSON_With_JavaScriptSerializer(getData());
            Console.WriteLine(JsonString2);

            Console.ReadKey();
        }

        public static DataTable getData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(Int32));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Designation", typeof(string));
            dt.Columns.Add("Location", typeof(string));
            dt.Rows.Add(1, "Sourabh Chauhan", "Software Developer", "Delhi");
            dt.Rows.Add(2, "Amit Mishra", "UX Designer", "Mumbai");
            dt.Rows.Add(3, "John Doe", "Project Manager", "Scottland");
            dt.Rows.Add(4, "Tommy Brown", "Electrician", "Sydney");
            dt.Rows.Add(5, "Vaibhav Sharma", "Network Engineer", "New Delhi");
            dt.Rows.Add(6, "Sankalp Sharma", "Accountant", "New York");
            dt.Rows.Add(7, "Raju Chauhan", "Mechanic", "Mumbai");
            dt.Rows.Add(8, "Jaden White", "Electrician", "Paris");
            dt.Rows.Add(9, "Raghav Yadav", "Web Designer", "Noida");
            dt.Rows.Add(10, "Dinesh Verma", "Team Leader", "Delhi");
            return dt;
        }
        public static string COnvert_DataTableToJSON_With_JavaScriptSerializer(DataTable dt)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
            Dictionary<string, object> childRow;
            foreach (DataRow row in dt.Rows)
            {
                childRow = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    childRow.Add(col.ColumnName, row[col]);
                }
                parentRow.Add(childRow);
            }
            return jsSerializer.Serialize(parentRow);
        }
    }
}

Method 3: Convert DataTable To JSON Format By Using StringBuilder in C#

In this method, first, we need to import System.Text. 

Here is the code to convert DataTable To Json Format in C#.

Example - Convert DataTable To JSON Format By Using StringBuilder in C#
using System;
using System.Data;
using System.Text;

namespace Tutorialsrack
{
    class Program
    {
        /* Convert DataTable to JSON Format using StringBuilder in C# */
        static void Main(string[] args)
        {
            Console.WriteLine("--Convert DataTable To JSON Format using StringBuilder--");
            string JsonString2 = Convert_DataTableToJSON_With_StringBuilder(getData());
            Console.WriteLine(JsonString2);

            Console.ReadKey();
        }

        public static DataTable getData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(Int32));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Designation", typeof(string));
            dt.Columns.Add("Location", typeof(string));
            dt.Rows.Add(1, "Sourabh Chauhan", "Software Developer", "Delhi");
            dt.Rows.Add(2, "Amit Mishra", "UX Designer", "Mumbai");
            dt.Rows.Add(3, "John Doe", "Project Manager", "Scottland");
            dt.Rows.Add(4, "Tommy Brown", "Electrician", "Sydney");
            dt.Rows.Add(5, "Vaibhav Sharma", "Network Engineer", "New Delhi");
            dt.Rows.Add(6, "Sankalp Sharma", "Accountant", "New York");
            dt.Rows.Add(7, "Raju Chauhan", "Mechanic", "Mumbai");
            dt.Rows.Add(8, "Jaden White", "Electrician", "Paris");
            dt.Rows.Add(9, "Raghav Yadav", "Web Designer", "Noida");
            dt.Rows.Add(10, "Dinesh Verma", "Team Leader", "Delhi");
            return dt;
        }
        public static string Convert_DataTableToJSON_With_StringBuilder(DataTable dt)
        {
            var JSON_String = new StringBuilder();
            if (dt.Rows.Count > 0)
            {
                JSON_String.Append("[");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JSON_String.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JSON_String.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JSON_String.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JSON_String.Append("}");
                    }
                    else
                    {
                        JSON_String.Append("},");
                    }
                }
                JSON_String.Append("]");
            }
            return JSON_String.ToString();
        }
    }
}

I hope this article will help you to understand how to convert DataTable To JSON format in C#.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!

 


Related Posts



Comments

Recent Posts
Tags