2013-05-04 119 views
0

我一直在試圖填補我的谷歌圖表動態地,像這樣的例子: https://developers.google.com/chart/interactive/docs/php_example谷歌圖 - 填充與JSON

我用這依賴於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 = 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 Chart卻說:'Table has no col UMS「。 谷歌的例子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}]} 
     ] 
} 

有沒有人有什麼我做錯了的想法?我需要做其他事嗎? Thanx提前。

回答

0

有點晚了,但晚一點再好一點。我想我知道你的問題的答案。

你其實知道答案。在你的問題中,你給出了一個Google Chart JSON示例。 JSON字符串需要開始與

{"cols":...} 

,而你的JSON字符串,由GSON呈現,與

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

開始。如果你傳遞一個JSON字符串到谷歌的DataTable的可視化,然後其結構需要看起來完全像谷歌示例。因此,而不是「列」,它需要是「cols」。

0

您可以使用API​​的JsonRenderer

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