Wednesday, September 4, 2013

C# - Convert Datatable to JSON String in C#, VB.NET

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:
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