Tuesday, 12 May 2015

How to Convert a DataTable into JSON formate in c# .NET ?

Here I pxplained how to convert a DataTable into JSON formate in c#.

 I used JavaScriptSerializer  to Serialize a List thats contains an object of Dictionary and this Dictionary contains of Column name as Index and Column value as Object. finally thsi List passed to JSSerializer.Serialize(ListObj) method


Surce Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.IO;
using System.Web;
using Newtonsoft.Json;

namespace ConsoleAppDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the DataTable.
            DataTable table =new DataTable();
            table = GetTable(table);
            //now Convert this table into JSON formate
            String json= GetJsonFormate(table);
            Console.WriteLine(json);
            Console.ReadKey();

           
        }

        static DataTable GetTable( DataTable table)
        {
          // Here I create a Employee DataTable with four columns.
            table.Columns.Add("EmpId", typeof(int));
            table.Columns.Add("EmpName", typeof(string));
            table.Columns.Add("Salary", typeof(int));
            table.Columns.Add("Company", typeof(string));

            // Here we add five DataRows.
            table.Rows.Add(101, "Ramu", 30000, "Kavin");
            table.Rows.Add(102, "Nanu", 35000, "Kavin");
            table.Rows.Add(103, "Sonu", 50000, "Kavin");
            table.Rows.Add(104, "Monu", 25000, "Kavin");
            table.Rows.Add(105, "Salu", 37000, "Kavin");
            return table;
        }
         static string GetJsonFormate(DataTable dt)
        {
            // Create an instance of JavaScript Serializer
            System.Web.Script.Serialization.JavaScriptSerializer JSSerializer = new
            System.Web.Script.Serialization.JavaScriptSerializer();

            // Create an instance of List thats contains an Object of Dictionary.
            List<Dictionary<string, object>> DtRows =
              new List<Dictionary<string, object>>();
            Dictionary<string, object> newrow = null;

            //Code to loop each row in the datatable and add it to the dictionary object
            foreach (DataRow drow in dt.Rows)
            {
                newrow = new Dictionary<string, object>();
                // Loop for each column
                foreach (DataColumn col in dt.Columns)
                {
                    newrow.Add(col.ColumnName.Trim(), drow[col]);
                }
                DtRows.Add(newrow);
            }

            //Serialising the dictionary object to produce json output
            JSSerializer.MaxJsonLength = Int32.MaxValue;

            return JSSerializer.Serialize(DtRows);
        }
    }

}



Output:-




No comments:

Post a Comment