Tarmizi Hamid Tarmizi Hamid - 1 month ago 16
JSON Question

How to get json object from controller in zul ZK?

I need to create a chart in zk using google chart, like below:
enter image description here

this is my controller:

public class ChartForm extends GenericComposer{

public List<Task> listTask;
public String json;

/* (non-Javadoc)
* @see org.zkoss.zk.ui.util.GenericComposer#doAfterCompose(org.zkoss.zk.ui.Component)
*/
@Override
public void doAfterCompose(Component comp) throws Exception {
// TODO Auto-generated method stub
super.doAfterCompose(comp);

TaskService ts = new TaskService();

listTask = ts.getTask();

json = new Gson().toJson(listTask); // I't OK until here

System.out.println(json);
}


}

The value is:


[{"taskName":"Automation","hours":11},{"taskName":"Manual","hours":2},{"taskName":"Report","hours":2},{"taskName":"Payroll","hours":2},{"taskName":"MISC","hours":7}]


My zul:

<zk>
<window id="HomePage" apply = "com.dom.form.ChartForm" border="none" width="100%" height="100%" style="background-color:green">
<script type="text/javascript" src="https://www.gstatic.com/chart/loader.js"></script>
<div id="piechart_3d" style="width: 500px; height: 300px;">
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Automation', 11],
['Manual', 2],
['Report', 2],
['Payroll', 2],
['MISC', 7]
]);

var options = {
title: 'My Daily Work Activities',
is3D: true,
};


var chart = new google.visualization.PieChart(zk.Widget.$("$piechart_3d").$n());
chart.draw(data, options);
}
</script>
</div>

</window>

</zk>


Now I need to get the json object and insert it into data (variable)

var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Automation', 11],
['Manual', 2],
['Report', 2],
['Payroll', 2],
['MISC', 7]
]);


Thanks before,

Tarmizi

Answer Source

you can use Clients.evalJavaScript(); to pass Json from controller to view, like this :

function drawChart(jsonObj){
  var data = JSON.parse(jsonObj);
  var chart = new google.visualization.PieChart(zk.Widget.$("$piechart_3d").$n());
  chart.draw(data, options);
}

and in your controller :

TaskService ts = new TaskService();
listTask = ts.getTask(); 
json = new Gson().toJson(listTask);
Clients.evalJavaScript("drawChart('" + json + "')");