[英]How to create the Google DataTable JSON expected source using C#?
如何使用C#創建google.visualization.datatable所期望的JSON源? 顯然使用JavaScriptSerializer
是不可能的,因為預期的JSON具有文檔中描述的奇怪結構:
var dt = new google.visualization.DataTable(
{
cols: [{id: 'task', label: 'Task', type: 'string'},
{id: 'hours', label: 'Hours per Day', type: 'number'}],
rows: [{c:[{v: 'Work'}, {v: 11}]},
{c:[{v: 'Eat'}, {v: 2}]},
{c:[{v: 'Commute'}, {v: 2}]},
{c:[{v: 'Watch TV'}, {v:2}]},
{c:[{v: 'Sleep'}, {v:7, f:'7.000'}]}
]
},
0.6
)
雖然我不熟悉.NET環境,但Google Visualization API有一個名為bortosky-google-visualization的.NET助手。 該庫從System.Data.DataTable
對象寫入JSON Google DataTable。
實現此目的的另一種方法是使用Google DataTable .Net Wrapper( https://googledatatablelib.codeplex.com/ ),它可以使用強類型的System.DataTable,然后可以將其轉換為google.datatable可視化JSON格式。
這個服務器端代碼
public string GetStatisticsForChart(string messageCode)
{
//some repository that returns data....
var data = _statisticsRepository.GetPerMessage(messageCode);
//It simply returns a list of objects with Year and Count properties.
var query = (from t in data
group t by new {t.TimeStamp.Year}
into grp
select new
{
grp.Key.Year,
Count = grp.Count()
}).ToList();
//let's instantiate the DataTable.
var dt = new Google.DataTable.Net.Wrapper.DataTable();
dt.AddColumn(new Column(ColumnType.String, "Year", "Year"));
dt.AddColumn(new Column(ColumnType.Number, "Count", "Count"));
foreach (var item in query)
{
Row r = dt.NewRow();
r.AddCellRange(new Cell[]
{
new Cell(item.Year),
new Cell(item.Count)
});
dt.AddRow(r);
}
//Let's create a Json string as expected by the Google Charts API.
return dt.GetJson();
}
將生成以下JSON輸出
{
"cols": [
{"type": "string", "id": "Year", "label": "Year"},
{"type": "number", "id": "Count", "label": "Count"}
],
"rows": [
{"c": [{"v": "2011"}, {"v": "1860"}]},
{"c": [{"v": "2012"}, {"v": "2000"}]}
]
}
這可以在Asp.NET WebAPI中使用,也可以直接在ASP.NET MVC控制器中使用。
上面示例中的預期JSON不是JSON,而是Javascript對象文字。 JSON只是Javascript對象文字表示法的一個子集,但如果使用類似的JSON初始化Google DataTable,上面的示例應該(並且確實)也可以。 (要獲得正確的JSON,只需在鍵周圍加上雙引號。)
實際上,您可以使用DataContractJsonSerializer
或JavaScriptSerializer
為Google DataTable構建JSON。 但是,如果您的起點是System.Data.DataTable
,則可能更容易使用上面答案中提到的庫。
通過c#創建谷歌圖表數據表的最佳方法是迭代數據並填充模型類並將填充的模型作為JSON返回,這里是模型表示: -
public class GChartsDataTbl
{
public List<Col> cols { get; set; }
public List<Row> rows { get; set; }
}
public class Col
{
public string id { get; set; }
public string type { get; set; }
}
public class C
{
public string v { get; set; }
public object f { get; set; }
}
public class Row
{
public List<C> c { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.