Introduction:
Here
I will explain how to convert asp.net datatable to JSON
string in C#, VB.NET or How to get JSON string from Datatable in in C#, VB.NET
Description:
In
previous posts I explained convert datatable to xml in asp.net, Convert datatable/dataset to arraylist, convert xml string to datatable in c#, asp.net, C#, SQL Server InterviewQuestions,send gridview as email body, upload and download files from gridview and many articlesrelating to asp.net,C#, VB.NET code snippets. Now I will explain howto convert datatable to JSONstring in asp.net using C#, VB.NET.
To
convert datatable to JSON string we need to write the code like as shown below
C#
Code
// This method is used to convert
datatable to json string
public string
ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection
con = new SqlConnection("Data Source=SureshDasari;Initial
Catalog=master;Integrated Security=true"))
{
using (SqlCommand
cmd = new SqlCommand("select
title=City,lat=latitude,lng=longitude,description from LocationDetails",
con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
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;
foreach (DataRow
dr in dt.Rows)
{
row = new Dictionary<string,
object>();
foreach (DataColumn
col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}Source : http://www.aspdotnet-suresh.com/2013/05/c-convert-datatable-to-json-string-in-c.html
No comments:
Post a Comment