Java REST API for supplying data to Google Charts

1,649 views
Skip to first unread message

Anthony Zepezauer

unread,
Jun 24, 2014, 6:32:08 PM6/24/14
to google-visua...@googlegroups.com
Hi, new here.  I'm trying to build a Google Charts application that gets its data from a REST API built in Java.  

Question 1 is, can anybody point me to some documentation on what needs to be returned from the Java side?  I should probably start by reading up but so far everything I've found is concerned with the javascript side of things, or on building a REST service in PHP.


More specifically, here is what I have tried and why it's not working:

My javascript code looks like this:

  <script type="text/javascript">
    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawChart);
    function drawChart() {

      var jsonData = $.ajax({
        url: "/rrportal-trd/api/productMetrics/activeCampaigns",
        dataType:"json",
        async: false
      }).responseText;

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);

      var options = {
        title: 'Active Campaigns'
      };

      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
  </script>

I first tried hard-coding the JSON as a String, basically as a 'hello world' first try:

    return "{" +
      "  cols: [{id: 'date', label: 'Date', type: 'string'}," +
      "         {id: 'activeCampaigns', label: 'Active Campaigns', type: 'number'}" +
      "        ]," +
      "  rows: [{c:[{v: new Date(2014, 6, 22), f: '2/28/08'}, {v: 393}]}," +
      "         {c:[{v: new Date(2014, 6, 23), f: '2/28/08'}, {v: 412}]}" +
      "        ]" +
      "}";

but this line barfed on the response:

      var data = new google.visualization.DataTable(jsonData);

HOWEVER, if I grab the response from Chrome developer tools and paste it directly into the javascript, then reload the page, it works perfectly:

      var data = new google.visualization.DataTable({  cols: [{id: 'date', label: 'Date', type: 'string'},         {id:
        'activeCampaigns', label: 'Active Campaigns', type: 'number'}        ],  rows: [{c:[{v: new Date(2014, 6, 22), f:
        '2/28/08'}, {v: 393}]},         {c:[{v: new Date(2014, 6, 23), f: '2/28/08'}, {v: 412}]}        ]});

Any idea what's needed to make that work?

Now I'm trying to build the response using google.visualization.DataTable and have a question about that, but this post is already very long, I will save that for another one.




Anthony Zepezauer

unread,
Jun 24, 2014, 8:22:05 PM6/24/14
to google-visua...@googlegroups.com

Re-reading my own post, I'm not sure if I was clear:  The code snippet that begins with

     return "{" + 

is Java code; it's what is returned by the api call 

           /rrportal-trd/api/productMetrics/activeCampaigns

Andrew Gallant

unread,
Jun 24, 2014, 8:39:57 PM6/24/14
to google-visua...@googlegroups.com
When you get the responseText of the AJAX call, it is a string, which must be parsed as JSON.  Your string construction, however, is not valid JSON (object keys and strings must be double-quoted, dates must be entered as strings like "Date(2014, 6, 23)").  When you copy the string into javascript like your example, it is valid, because you are pasting a javascript object that way, not a JSON string.  A properly analagous test would be to put quotes around the object:


var data = new google.visualization.DataTable("{  cols: [{id: 'date', label: 'Date', type: 'string'},         {id:        'activeCampaigns', label: 'Active Campaigns', type: 'number'}        ],  rows: [{c:[{v: new Date(2014, 6, 22), f:        '2/28/08'}, {v: 393}]},         {c:[{v: new Date(2014, 6, 23), f: '2/28/08'}, {v: 412}]}        ]}");

which fails.

Since you are using Java, I recommend importing either the jackson or gson libraries to perform JSON encoding of POJOs into JSON strings.  You can then construct a Java object to represent your data and use the libraries to convert it to JSON for you.  Here's a rough start on what such an object might look like:

public class DataTable {
    private List<Column> cols; // list of columns
    private List<Row> rows; // list of rows
   
    // constructor, getters, and setters
   
    private class Column {
        private String type; // type of column
        private String id; // id of column
        private String label; // label of column
        private Map<String, Object> p; // properties of column
       
        // constructor, getters, and setters
    }
   
    private class Row {
        private List<Cell> c; // list of cells
        private Map<String, Object> p; // properties of row
       
        // constructor, getters, and setters
       
        private class Cell {
            private Object v; // value of cell
            private string f; // formatted value of cell
            private Map<String, Object> p; // properties of cell
           
            // constructor, getters, and setters
        }
    }
}


You also may want to look into the Java DataSource Library, which is intended to implement the data source protocol, but can probably be used piecemeal for custom projects as well.

Anthony Zepezauer

unread,
Jun 24, 2014, 8:58:45 PM6/24/14
to google-visua...@googlegroups.com
Thanks Andrew, I believe we have Jackson installed and wired into all our web services, so I was assuming it would magically transform my string into JSON.  I'll try your approach with the DataTable and see if I can get that working.

(FWIW, while waiting for replies I continued to experiment with the string and found that this worked:

    return "{" +
      "  \"cols\": [" +
      "        {\"id\":\"\",\"label\":\"Date\",\"pattern\":\"\",\"type\":\"string\"}," +
      "        {\"id\":\"\",\"label\":\"Active Campaigns\",\"pattern\":\"\",\"type\":\"number\"}" +
      "      ]," +
      "  \"rows\": [" +
      "        {\"c\":[{\"v\":\"6/20/14\",\"f\":null},{\"v\":393,\"f\":null}]}," +
      "        {\"c\":[{\"v\":\"6/21/14\",\"f\":null},{\"v\":387,\"f\":null}]}," +
      "        {\"c\":[{\"v\":\"6/22/14\",\"f\":null},{\"v\":406,\"f\":null}]}," +
      "        {\"c\":[{\"v\":\"6/23/14\",\"f\":null},{\"v\":411,\"f\":null}]}," +
      "        {\"c\":[{\"v\":\"6/24/14\",\"f\":null},{\"v\":415,\"f\":null}]}" +
      "      ]" +
      "}";



Reply all
Reply to author
Forward
0 new messages