我正在使用 jquery 从 servlet 返回一个基本的 JSON 对象,它工作得非常好,但是我在格式化 JSON 以实际填充图表时遇到了麻烦。
这是调用 servlet 的代码:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.getJSON('SearchServlet', {servletAction: 'getSummary'}, function(json) {
var data = new google.visualization.DataTable(json);
var chart = new google.visualization.PieChart(document.getElementById('summaryPieChart'));
chart.draw(data, {backgroundColor:'#e9f1f4',width: '90%', height: '90%', legend:{position:'none'}, chartArea:{width:"90%",height:"90%"},colors:['#94d784','#d78484']});
});
}
在 servlet 方面,我用来创建 JSON 的代码是:
private int positive;
private int negative;
private int neutral;
public DataTable createResultsJSON(){
DataTable data = new DataTable();
ArrayList<ColumnDescription> cols = new ArrayList<ColumnDescription>();
cols.add(new ColumnDescription("summary", ValueType.TEXT, "Summary"));
cols.add(new ColumnDescription("result", ValueType.NUMBER, "Result"));
data.addColumns(cols);
try {
data.addRowFromValues("positive", positive, true);
data.addRowFromValues("negative", negative, true);
data.addRowFromValues("neutral", neutral, true);
} catch (TypeMismatchException e) {
System.out.println("Invalid type!");
}
return data;
}
使用以下方法将其转换为 JSON:
String resultJson = new Gson().toJson(createResultsJSON());
结果 JSON 的一个示例是:
{
"columns":[
{"id":"summary","type":"TEXT","label":"Summary","pattern":""},
{"id":"result","type":"NUMBER","label":"Result","pattern":""}],
"columnIndexById":{"result":1,"summary":0},
"rows":[
{"cells":[{"value":{"value":"positive"}},{"value":{"value":362.0}}]},
{"cells":[{"value":{"value":"negative"}},{"value":{"value":302.0}}]},
{"cells":[{"value":{"value":"neutral"}},{"value":{"value":349.0}}]}],
"warnings":[]
}
但是,根据 Google Chart 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}]}
]
}
我已经尝试了多种不同的方法来在服务器端正确格式化 JSON,但仍然卡住了,我相信这是一个快速简单的修复,因此感谢您的帮助。
当查询获取 JSON 并尝试处理它时,它会显示“表没有列”
谢谢