How to convert data table into JSON in C#?

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string server = Request.QueryString["username"].ToString();
        string database = Request.QueryString["password"].ToString();
        SqlConnection con = new SqlConnection("database=" + database + ";server=" + server + "; integrated security=true;");

        string str = "select * from employee";
        SqlDataAdapter da = new SqlDataAdapter(str, con);
        DataTable dt = new DataTable();
        da.Fill(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);
        }
        jsSerializer.Serialize(parentRow);
        Response.Write(jsSerializer.Serialize(parentRow));
    }
}
Share:

No comments:

Post a Comment

Tuesday, 16 February 2016

How to convert data table into JSON in C#?

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string server = Request.QueryString["username"].ToString();
        string database = Request.QueryString["password"].ToString();
        SqlConnection con = new SqlConnection("database=" + database + ";server=" + server + "; integrated security=true;");

        string str = "select * from employee";
        SqlDataAdapter da = new SqlDataAdapter(str, con);
        DataTable dt = new DataTable();
        da.Fill(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);
        }
        jsSerializer.Serialize(parentRow);
        Response.Write(jsSerializer.Serialize(parentRow));
    }
}

No comments:

Post a Comment

Popular

Total Pageviews

Archive