Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create the Google DataTable JSON expected source using C#?

How can I create the JSON source expected by the google.visualization.datatable using C#? Obviously using the JavaScriptSerializer is out of the question since the expected JSON has a weird structure as described on the documentation:

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
)
like image 504
Raúl Roa Avatar asked Feb 04 '23 05:02

Raúl Roa


2 Answers

Though I'm not familiar in the .NET environment, there is a .NET helper for the Google Visualization API called bortosky-google-visualization. The library writes a JSON Google DataTable from a System.Data.DataTable object.

like image 103
viam0Zah Avatar answered Feb 07 '23 12:02

viam0Zah


Another way to achieve this is to use the Google DataTable .Net Wrapper (https://googledatatablelib.codeplex.com/) which gives a possibility to work with a strongly typed System.DataTable that can then be converted into the google.datatable visualization JSON format.

This server side code

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();
}

would generate the following JSON output

{
    "cols": [
            {"type": "string", "id": "Year",  "label": "Year"}, 
            {"type": "number", "id": "Count", "label": "Count"}
        ], 
    "rows": [
            {"c": [{"v": "2011"}, {"v": "1860"}]}, 
            {"c": [{"v": "2012"}, {"v": "2000"}]}
        ]
}

and this can be used either in Asp.NET WebAPI or directly in the ASP.NET MVC controller.

like image 45
zoranmax Avatar answered Feb 07 '23 12:02

zoranmax