richardb
richardb

Reputation: 33

Google Chart JSON Issue - Java

I'm using jquery to return a basic JSON object from a servlet, which is working absolutely fine, however I'm having trouble formatting the JSON to actually populate the chart.

This is the code that is calling the 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']});
    });

}

On the servlet side, the code I'm using to create the JSON is:

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;
}

Which is converted to a JSON using:

String resultJson = new Gson().toJson(createResultsJSON());

An example of the result JSON is:

{
"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":[]
}

However, according to the Google Chart JSON specifications, it should be should resemble something like the following:

{
"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}]}
  ]

}

I've tried a number of different approaches to formatting the JSON correctly on the server side and am still stuck, I'm sure it's a quick and easy fix so any help is appreciated.

When query gets the JSON and tries to handle it, it says "Table Has No Columns"

Thanks

Upvotes: 1

Views: 3125

Answers (2)

Bharathi Jeganathan
Bharathi Jeganathan

Reputation: 1

Create the Json for data table with JSON Renderer like below.

JsonNode root = null;
String json = JsonRenderer.renderDataTable(data, true, false).toString();

        try{
            JsonParser parser = new JsonFactory().createJsonParser(json)
                .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
                .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
                 root = new ObjectMapper().readTree(parser);
            }catch(Exception e){
              e.printStackTrace();
            }

return root.toString();

Json will be in required format for google chart api. It worked for me.

Upvotes: 0

m suresh
m suresh

Reputation: 659

create the string instead of json. that string put in request scope and directly get that string in jsp(request.getAttribute());

var data = new google.visualization.DataTable(request.getAttribute());

i did this i got answer..

Upvotes: 3

Related Questions