سؤال

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
)
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

The expected JSON in the example above is not JSON but a Javascript object literal. JSON is only a subset of Javascript object literal notation, but the example above should (and does) also work, if the Google DataTable is initialized with a similar looking JSON. (To get proper JSON just put double quotes around the keys.)

So actually you can use the DataContractJsonSerializer or JavaScriptSerializer to construct JSON for the Google DataTable. However, if your starting point is a System.Data.DataTable it is probably easier to use the library mentioned in the answer above.

The best way to create google charts datatable via c# is to iterate data and fill model class and return filled model as JSON , here is the model representation :-

 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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top