Over a million developers have joined DZone.

Drawing Google Chart From Servlet JSON Response

DZone's Guide to

Drawing Google Chart From Servlet JSON Response

· Java Zone
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

  • Google provides Visualization API to draw charts and other components.
  • More Details can be found on :-
  • Different type of ready to use chart types are exposed a java script classes to the developers for customize.
  • In this Demo"We will see how a visualization charts get rendered in browser for a JSON data response from a Servlet".
  • Project Structure,
  • The java servlet uses GSON API jar library for converting a array list of student data to its JSON representation.
           StudentJsonDataServlet.java code below, 

package com.sandeep.visual.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.sandeep.visual.data.Student;

public class StudentJsonDataServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;

 public StudentJsonDataServlet() {

 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  List<Student> listOfStudent = getStudentData();

  Gson gson = new Gson();

  String jsonString = gson.toJson(listOfStudent);




 private List<Student> getStudentData() {

  List<Student> listOfStudent = new ArrayList<Student>();
  Student s1 = new Student();

  Student s2 = new Student();

  Student s3 = new Student();

  Student s4 = new Student();

  return listOfStudent;

  • The JSON response data format is as below,
  •  The HTML markup is present in visualization-chart-demo.html file,
  <title>Google Visualization Chart Demo</title>
  <div id="student-bar-chart"></div>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript" src="./js/visualization-chart-script.js"></script>
  • The above html has a "DIV#student-bar-chart" html element for bar chart container.It calls JQUERY and JSAPI library from Google hosted CDN.Finally it calls our script code present in 
    visualization-chart-script.js file.

 /*return google visualization data*/
 getvisualizationData: function (jsonData) {

  var point1, point2, dataArray = [],

   data = new google.visualization.DataTable();

  data.addColumn('string', 'Name');

  data.addColumn('number', 'Marks in Mathematics');

    type: 'string',
    role: 'tooltip',
    'p': {
     'html': true

  data.addColumn('number', 'Marks In Computer');

    type: 'string',
    role: 'tooltip',
    'p': {
     'html': true

  /* for loop code for changing inputdata to 'data' of type google.visualization.DataTable*/
  $.each(jsonData, function (i, obj) {

   point1 = "Math : " + obj.mathematicsMark + "";

   point2 = "Computer : " + obj.computerMark + "";

   dataArray.push([obj.name, obj.mathematicsMark, TUTORIAL_SAVVY.returnTooltip(point1, point2), obj.computerMark, TUTORIAL_SAVVY.returnTooltip(point1, point2)]);


  return data;
 /*return options for bar chart: these options are for various configuration of chart*/
 getOptionForBarchart: function () {

  var options = {
   animation: {
    duration: 2000,
    easing: 'out'

   hAxis: {
    baselineColor: '#ccc'
   vAxis: {
    baselineColor: '#ccc',
    gridlineColor: '#fff'

   isStacked: true,
   height: 400,
   backgroundColor: '#fff',
   colors: ["#68130E", "#c65533"],
   fontName: 'roboto',
   fontSize: 12,
   legend: {
    position: 'top',
    alignment: 'end',
    textStyle: {
     color: '#b3b8bc',
     fontName: 'roboto',
     fontSize: 12
   tooltip: {
    isHtml: true,
    showColorCode: true,
    isStacked: true
  return options;
 /*Draws a Bar chart*/
 drawBarChart: function (inputdata) {

  var barOptions = TUTORIAL_SAVVY.getOptionForBarchart(),

   data = TUTORIAL_SAVVY.getvisualizationData(inputdata),

   chart = new google.visualization.ColumnChart(document.getElementById('student-bar-chart'));

  chart.draw(data, barOptions);
  /*for redrawing the bar chart on window resize*/
  $(window).resize(function () {

   chart.draw(data, barOptions);
 /* Returns a custom HTML tooltip for Visualization chart*/
 returnTooltip: function (dataPoint1, dataPoint2) {

  return "<div style='height:30px;width:150px;font:12px,roboto;padding:15px 5px 5px 5px;border-radius:3px;'>" +
   "<span style='color:#68130E;font:12px,roboto;padding-right:20px;'>" + dataPoint1 + "</span>" +
   "<span style='color:#c65533;font:12px,roboto;'>" + dataPoint2 + "</span></div>";
 /*Makes ajax call to servlet and download data */
 getStudentData: function () {


    url: "StudentJsonDataServlet",

    dataType: "JSON",

    success: function (data) {


google.load("visualization", "1", {
  packages: ["corechart"]

$(document).ready(function () {

  • The above javascript has following function with its purpose:-
         getStudentData() ----- On DOM ready it makes an AJAX call and download the Student data.
         drawBarChart()------ On SUCCESS of AJAX call this method get called.
 getOptionForBarchart()-----Return the CONFIGURATION for bar chart.
 getvisualizationData()------Formats the JSON data to Google Visualization Data format.
         returnTooltip()-------Returns the HTML string for CUSTOM tooltip. 
  • The output bar chart :-

  • Download Link for the Demo project:-
          project download link

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.


Published at DZone with permission of Sandeep Patel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}