C# Json Response

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class tryJson : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
Response.Write(ConvertDataTabletoString());
Response.End();
}
public string ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(“Data Source = localhost\\SQLEXPRESSARD; Initial Catalog = ArduinoData; User Id = Arduino_User; Password = arduinodata;”))
{
using (SqlCommand cmd = new SqlCommand(“SELECT TOP 20 replace(convert(char(10),Timestamp,102),’.’,’-‘) as label ,[Ampere5] as value FROM [ArduinoData].[dbo].[DataLogTenB] ORDER BY id ASC”, 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);
}
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s