我正在尝试将SQL存储过程的结果转换为DataTable并将其转换为Json,因此稍后我可以将它与Highcharts一起使用。出于某种原因,我得到的结果格式错误:
我的控制器:
public ActionResult GetDailyOutputByHour(int machine, string dateFrom, string dateTo, string line = "All")
{
Graph g = repository.Graphs.Where(p => p.GraphID == 1).FirstOrDefault();
string result = repository.GetGraphData(g.StoredProc + " '" + line + "', " + machine + ", '" + dateFrom + "', '" + dateTo + "'");
return Content(result, "application/json");
}
存储库:
public string GetGraphData(string sp)
{
var connection = ConfigurationManager.ConnectionStrings["EFDbContext"].ConnectionString;
using (var dataAdapter = new SqlDataAdapter("exec " + sp, connection))
{
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
dataAdapter.FillSchema(dataTable, SchemaType.Mapped);
string json = JsonConvert.SerializeObject(dataTable, Formatting.Indented);
return json;
}
}
我得到的结果:
"[\r\n {\r\n \"Hour\": 7,\r\n \"Input\": 4614,\r\n \"Output\": 2952,\r\n \"InTarget\": 3033,\r\n \"OutTarget\": 2533\r\n },\r\n {\r\n \"Hour\": 8,\r\n \"Input\": 3729,\r\n \"Output\": 2940,\r\n \"InTarget\": 3033,\r\n \"OutTarget\": 2533\r\n },\r\n {\r\n \"Hour\": 9,\r\n \"Input\": 4158,\r\n \"Output\": 3798,\r\n \"InTarget\": 3033,\r\n \"OutTarget\": 2533\r\n },\r\n {\r\n \"Hour\": 10,\r\n \"Input\": 5310,\r\n \"Output\": 4023,\r\n \"InTarget\": 3033,\r\n \"OutTarget\": 2533\r\n },\r\n {\r\n \"Hour\": 11,\r\n \"Input\": 1344,\r\n \"Output\": 2547,\r\n \"InTarget\": 3033,\r\n \"OutTarget\": 2533\r\n }\r\n]"
我做错了什么?
答案 0 :(得分:0)
你实际上得到了正确的输出老板,我认为这是错误的方式 您应该在Visual Studio中使用Text Visualizer查看输出,以便我认为您的输出正常
DataSet ds = new DataSet();
DataTable dt;
DataRow dr;
DataColumn objstrError;
DataColumn objBytearr;
dt = new DataTable();
objstrError = new DataColumn("strID", Type.GetType("System.String"));
objBytearr = new DataColumn("strName", Type.GetType("System.String"));
dt.Columns.Add(objstrError);
dt.Columns.Add(objBytearr);
dr = dt.NewRow();
dr["strID"] = "1";
dr["strName"] = "Britains got talent";
dt.Rows.Add(dr);
string json =JsonConvert.SerializeObject(dt,Newtonsoft.Json.Formatting.Indented);
normal intelisense gives:"[\r\n {\r\n \"strID\": \"1\",\r\n \"strName\": \"Britains got talent\"\r\n }\r\n]"
using TextVisualizer if you see it then looks like this:[
{
"strID": "1",
"strName": "Britains got talent"
}
]