Google Chart - 使用JSON填充

时间:2013-05-04 13:08:57

标签: json servlets charts

我一直试图动态填充我的Google图表,例如: https://developers.google.com/chart/interactive/docs/php_example

我正在为DataTable类和其他人使用此依赖项:

<dependency>
    <groupId>com.google.visualization</groupId>
    <artifactId>visualization-datasource</artifactId>
    <version>1.1.1</version>
</dependency>

这是DataTable类的API: https://developers.google.com/chart/interactive/docs/dev/dsl_javadocs/com/google/visualization/datasource/datatable/DataTable

我正在使用包含此代码(示例)的Java HttpServlet来填充DataTable:

DataTable dataTable = new DataTable();
dataTable.addColumn(new ColumnDescription("uur", ValueType.TEXT, "Uur"));
dataTable.addColumn(new ColumnDescription("aantal", ValueType.NUMBER, "Aantal spellen"));        
try {
    dataTable.addRowFromValues("1", 5, true);
    dataTable.addRowFromValues("2", 9, true);
    dataTable.addRowFromValues("3", 17, true);
} catch (TypeMismatchException ex) {
    Logger.getLogger(VerkrijgChartDataServlet.class.getName()).log(Level.SEVERE, null, ex);
}

我还包含了这个以使其返回JSON:

response.setContentType("application/json");

然后使用Gson我将其转换为JSON字符串:

new Gson().toJson(dataTable);

返回格式为

的字符串
{
  "columnIndexById" : {"aantal":1, "uur":0},
  "columns" : [
      {"id":"uur","label":"Uur","pattern":"","type":"TEXT"},
      {"id":"aantal","label":"Aantal spellen","pattern":"","type":"NUMBER"}
    ],
  "rows" : [ 
      {"cells":[{"value":{"value":"1"}},{"value":{"value":5.0}}]},
      {"cells":[{"value":{"value":"2"}},{"value":{"value":9.0}}]},
      {"cells":[{"value":{"value":"3"}},{"value":{"value":17.0}}]},
    ],
  "warnings" : []
}

但谷歌图表说:'表没有列。' Google的示例JSON如下所示:

{
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
      ]
}

有没有人知道我做错了什么?我还需要做点什么吗? 提前完成。

2 个答案:

答案 0 :(得分:0)

有点迟,但迟到,从来没有。我想我知道你问题的答案。

你真的知道答案。在您的问题中,您提供了Google Chart JSON示例。 JSON字符串需要以

开头
{"cols":...}

,而由gson呈现的JSON字符串以

开头
{"ColumnIndexById":{...},
 "columns":...
}

如果您将json字符串传递给Google DataTable可视化,那么其结构需要与Google示例完全相同。因此,它不是“列”,而是“cols”。

答案 1 :(得分:0)

您可以使用API​​的JsonRenderer

JsonRenderer.renderJsonResponse(
   DataSourceParameters.getDefaultDataSourceParameters(), null, data
)