2010-03-02 57 views
8

如何使用C#創建google.visualization.datatable預期的JSON源?顯然,使用JavaScriptSerializer是出了問題,因爲預期的JSON有作爲對文檔的描述一個奇怪的結構:如何使用C#創建Google DataTable 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 
) 

回答

8

雖然我不是在.NET環境熟悉,沒有爲一個.NET幫手Google Visualization API調用bortosky-google-visualization。該庫從System.Data.DataTable對象寫入JSON Google DataTable。

+0

正是我一直在尋找。非常感謝你。 – 2010-03-04 20:01:55

+1

對於Asp.net MVC Razor不是有用的。另外我不使用ADO.NET。 – RohannG 2014-07-01 07:30:00

1

上述示例中的預期JSON不是JSON,而是Javascript對象字面量。 JSON只是Javascript對象字面表示法的一個子集,但如果Google DataTable使用類似的JSON進行初始化,則上面的示例也應該可以工作。 (爲了得到正確的JSON,只需在鍵的周圍加雙引號)。

所以實際上,您可以使用DataContractJsonSerializerJavaScriptSerializer爲Google DataTable構建JSON。但是,如果您的出發點是System.Data.DataTable,則可能更容易使用上述答案中提到的庫。

2

實現此目的的另一種方法是使用Google DataTable .Net包裝器(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控制器使用。

0

通過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; } 
} 
相關問題