Displaying Table has no Columns using Google Charts - java

Trying to change the format of JSON to make it readable for Google charts.
The JSON content is working fine and currently displaying this on the browser:
[["name","cost"],["godzilla",12],["harry potter",12]]
The Task is being performed by a spring controller
#RequestMapping(value = "api/productschart", method = RequestMethod.GET)
public #ResponseBody
String listProductsJsonChart () throws JSONException {
JSONArray ProductArray = new JSONArray();
JSONArray ProductHeader = new JSONArray();
ProductHeader.put("id");
ProductHeader.put("cost");
ProductArray.put(ProductHeader);
for (Product product : productRepository.findAll()) {
JSONArray ProductJSON = new JSONArray();
ProductJSON.put(product.getId());
ProductJSON.put(product.getCost());
ProductArray.put(ProductJSON);
}
return ProductArray.toString();
}
The JavaScript section
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "http://localhost:8081/api/productschart",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data);
}
</script>

The examples on Google's pages use single quotes because they use JavaScript to build objects and JavaScript supports both single and double quotes. JSON, on the other hand, requires double quotes.
table has no columns
From the example at https://developers.google.com/chart/interactive/docs/gallery/columnchart#Data_Format, I think your JSON should look like this:
[["id","cost"],["1",12]]
i.e. the first item in the data part of the array needs to be a string. In your case, it's a number.

Related

Parse the json string : receiving from a java code

I need to send the string s or json to ajax .done function. Here is the servlet code that has an object list to be sent for an ajax request.
Gson gson = new Gson();
Tester t = new Tester(10,"s");
Tester t2 = new Tester(20,"g");
LinkedList<Tester> list = new LinkedList<Tester>();
list.add(t); list.add(t2);
String s = gson.toJson(list);
I need to send the json to ajax. How could I do this? I could do :
out.println(s);
But how would I then parse the string? I need to appropriately put the json data received into the html table.
The current json output from out.println(s) is [{"x":10,"y":"s"},{"x":20,"y":"g"}]
js function that will receive json :
function getFeFeeds() {
$.ajax( {
url : '',
dataType : 'json',
type : 'GET'
}).done(function(message) {
}).fail(function(message) {
});
}}
You need to iterate over the received json and do your processing -
$.each(message, function(index, row) {
console.log(row[0].x);
console.log(row[0].y);
});
Also I would suggest set encoding so that you don't have any encoding related issues -
response.setCharacterEncoding("UTF-8");

How to pass JSON array from Struts 2 action class to jQuery?

I creating a Java web application with an action file which generates data from database to a JSON array. Now, I want this JSON array to be passed to jQuery? How is that possible?
FYI. I applied Struts 2, Spring and Hibernate frameworks. I am not using PHP for this app.
Update:
This is my Struts 2 action method:
public static String jsonData = null;
public String generateJson() throws Exception
{
JSONObject json = null;
JSONArray jsonArray = new JSONArray();
this.records = this.recordManager.getAllRecords();
for (RecordEntity record : records)
{
json = new JSONObject();
json.put("id", record.getId());
json.put("firstname", record.getFirstName());
json.put("lastname", record.getLastName());
json.put("due", record.getDue());
json.put("email", record.getEmail());
json.put("website", record.getWebsite());
jsonArray.put(json);
}
System.out.println(jsonArray.toString());
jsonData = jsonArray.toString(); // jsonData will be passed to jQuery
return SUCCESS;
}
And this is my jQuery. I am using BootstrapTable so this is the structure, and I want the value of jsonData to be passed to this jQuery:
$('#record').bootstrapTable({
method : 'get',
data: jQuery.parseJSON(VALUE_OF_jsonData_HERE),
cache : ...
...
...
});
Using Ajax will help you,
refer this to get started, also do read about Ajax first to have a background

How to display the values java object array in jquery

I have returned the object array from scriptlet,
<%
List list = new BaseHibernateDAO().executeSQLQuery(queryString);
Object[] data = (Object[]) list.get(0);
out.print(data);
%>
When i tried to get values in jquery it is not showing,
$.ajax({
url: URL,
success: function(data) {
alert(data);
}
});
it is showing as => [Ljava.lang.Object;#22649e15
default toString return classname +# + hashcode.. You have to override toString method. refer this SO link..
A clean approach would be to use some JSON marshaller to convert your Java objects to JSON format. In Javascript you can easily process JSON as it is natively supported.
In Java EE 7 you can use the build-in JSON libraries (in earlier versions you can use e.g. Jackson):
JsonObject value = Json.createObjectBuilder()
.add("field1", "1")
.add("field2", "2")
.build();
JsonWriter writer = Json.createWriter(out);
writer.writeObject(value);

Retrieve JSON object after jQuery get finish

I'm trying to retrieve JSON object using jQuery get, and the Object I retrieve I want to embed in innerHTML. The following code is how i construct my JSON
getListOfActivity.jsp
<%
String urusStr = request.getParameter("ukid");
int urusId = Integer.parseInt(urusStr);
lkpPdkCommon[] activity = getListOfActivity(urusId);
if(activity!=null){
out.println("{PartList:");
out.println("[");
for(int x=0;x<2;x++){// the lkpPdkCommon[] return from getListOfActivity(urusId) huge so I limit the array to 2
out.println("{");
out.println("ActivityID:\""+activity[x].getID()+"\",Description:\""+activity[x].getDescription()+"\"");
out.println("}");
if((x+1)!=2){
out.println(",");
}
}
out.println("]");
out.println("}");
response.setContentType("application/json");
%>
and below code is my jQuery/jscript
var ukid = document.getElementById("ukid").value
var aktivityId = row.insertCell(1);
var description = row.insertCell(2);
var JSONObject;
var $ac = jQuery.noConflict();
$ac.get("../../getListOfActivity.jsp",{ukid:ukid}, function(data){
JSONObject = data
//for testing purposes I do not iterate through the JSON Object
aktivityId.innerHTML = JSONObject.PartList[0].ActivityID
description.innerHTML = JSONObject.PartList[0].Description
});
The following code didn't return any error, but it seems doesn't work. This is the JSON Object I check using firebug
Have you tried Jquery getJSON.
I think this would help you.
http://api.jquery.com/jQuery.getJSON/
The problem solved after I modified the following line in jsp
out.println("{PartList:");
to
out.println("{\"PartList\":");
and
out.println("ActivityID:\""+activity[x].getID()+
"\",Description:\""+activity[x].getDescription()+"\"");
to
out.println("\"ActivityID\":\""+activity[x].getID()+
"\",\"Description\":\""+activity[x].getDescription()+"\"");
The original JSON object send by response header before I do the modification are like below:
{PartList:
[
{ActivityID:"8638",Description:"GERMS"},
{ActivityID:"8639",Description:"GOVERNMENT CERTIFY PROGRAMMES"}
]
}
and after the modification
{"PartList":
[
{"ActivityID":"8638","Description":"GERMS"},
{"ActivityID":"8639","Description":"GOVERNMENT CERTIFY PROGRAMMES"}
]
}

Jquery autocomplete issue

I am new to jQuery and am trying to use the autocomplete widget with an ajax call to my database.
I am able to call the database, returned ArrayList of string values, and converted the response as a JSON object using org.codehaus.jackson.map.ObjectMapper (Do I need to use something else?).
When I put an altar, I can see results as pure strings with comma delimiter, but am not able to see a suggestion list with autocomplete.
Java code that returns the JSON object using org.codehaus.jackson.map.ObjectMapper:
response.setContentType("application/json");
response.setHeader("cache-control", "no-cache");
ArrayList polNo = doa.getPolicyData(ajaxForm.getPolicyNumber());
ObjectMapper mapper = new ObjectMapper();
OutputStream out = response.getOutputStream();
mapper.writeValue(out, polNo);
JavaScript code:
$( "#policyNumber" ).autocomplete({
source: function (request,response){
$.ajax({
type: "POST",
url: "/NB/AjaxSubmit.do",
dataType: "json",
data: {policyNumber: request.term},
success: function (data) {
alert(data);
}
});
},minLength: 3
});
alert data showing as : TMA412732,TMA412733,TMA412734
In above code, I have returned ArrayList of string values and was able to show in autopopulate. I have enhanced the above code to return list of person objects that has first name, last name etc. Now when user typing the firname or last name in the autopopulate , I would like to suggest First name, LastName Middle.
Could someone help to enhance this? Thanks!
success: function(data) {
response(data);//u forgot to set data on response
}
Change success function like
success: function (data) {
response(data); //u forgot to set data on response
}

Categories