Ajax call to retrieve hashmap - java

I have a hashmap which I have converted into a JSONObject. This JSONObject I am retrieving via a REST api using an AJAX call. What I wish to know is that how will the ajax look like in order to get the JSONObject which I can use afterwards.
My ajax call looks like this :
Ext.Ajax.request({
url : '...',
method:'GET',
scope : this,
success : function(result, request) {
console.log("2");
var data = Ext.decode(result.responseText)[0];
for (var i = 0; i < data.size(); i++) {
console.log("4. ");
}
}
})
The error which appears is
Ext.Error: You're trying to decode an invalid JSON String:

result.responseText returns the Invalid JSON String.Use this code
var responseArray = Ext.decode(response.responseText);
var data = responseArray.data;
console.log(data);
data variable will contain the JSON Object.

Related

AngularJS $http get return null status 0

I'm trying to create $http get request to fetch some json data generated by my web service, but it returns null error. However, the $http request works fine when I use this sample url instead (it returns json string too)
This is my angular code :
angular.module('ionicApp', ['ionic'])
.controller('ListCtrl', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get("http://localhost:8080/InventoryCtrl_Service/webresources/IVC_Service/GetUserList")
.then(function(response) {
console.log("success ");
},
function(response) {
console.log("Error : " + response.data + " Status : " + response.status);
}
});
This is my web service code :
#GET
#Path("/GetUserList")
#Produces("application/json")
public Response GetUserList() throws SQLException {
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject outerObject = new JSONObject();
JSONArray arr = new JSONArray();
obj1.put("Name", "Sara");
obj2.put("Name","David");
arr.add(obj1);
arr.add(obj2);
outerObject.put("records", arr);
return Response.status(200).entity(outerObject.toString()).build();
}
When I run the above code, it returns json string like this :
{"records":[{"Name":"Sara"},{"Name":"David"}]}
The console log returns this :
Error : null Status : 0
What is the meaning of the null error? Or is there anything wrong with how I return the json string?
Try using JSON_STRINGIFY, this will convert your incoming data into String format.
console.log(JSON_STRINGIFY(response.data));
TO verify what data your web service is returning, you can always check it by hitting your web service via postman.
I managed to solve this by adding CORS (Access-Control-Allow-Origin) to the response header, based on another SO answer. There's no problem with my angular code, it's just that I need to modify my web service code to enable the CORS. So I just modified the part where it returns data to become like this :
return Response.status(200).entity(outerObject.toString()).header("Access-Control-Allow-Origin", "*").build();

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

Pass data from Bean to javascript on jsf page. Google api directions

I need to pass waypoints to google maps javascript directions api from ManagedBean to jsf page.
I'm trying to make JSONArray and pass it to jsf:
private JSONArray routesJSON;
with getters and setters.
Than im creating JSON : in loop im adding Strings with LatLang of waypoints to List<String>
routes.add("new google.maps.LatLng(" + o.getLatitude() + "," + o.getLongitude()+")");
And im getting JSON :
[{"location":"new google.maps.LatLng(50.495121,22.1705)"},{"location":"new google.maps.LatLng(50.57082,22.06813)"},{"location":"new google.maps.LatLng(50.570549,22.047871)"},{"location":"new google.maps.LatLng(50.521389,21.912695)"},{"location":"new google.maps.LatLng(50.495121,22.1705)"}]
from:
for()
array.put(obj);
}
System.out.println(array);
in JSF function for displaying route : (it works with hardcoded data)
function calcRoute() {
var waypts = [];
var start = new google.maps.LatLng(#{someBean.startLatitude}, #{someBean.startLongitude});
var end = new google.maps.LatLng(49.712112, 21.50667);
var way = #{someBean.routesJSON};
var request = {
origin:start,
destination:end,
optimizeWaypoints: true,
waypoints:way;
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
But when im displaying that page map doesnt appear. I know it's probably because of " in JSON but i dont know how to remove it. Or may there are easiest ways to pass waypoint data from Bean to jsf page?
Instead of returning a JSON data packet that contains javascript statements like "new google.maps.LatLng(50.495121,22.1705)", it's more sensible to return just the coordinates.
So if you had a JSON packet that looks like this in your javascript (I don't know how to pass data between your Java and Javascript):
var routes = [
{"lat":"50.495121", "lng":"22.1705"},
{"lat":"50.57082", "lng":"22.06813"},
{"lat":"50.570549", "lng":"22.047871"},
{"lat":"50.521389", "lng":"21.912695"},
{"lat":"50.495121", "lng":"22.1705"}
]
You can turn this into an array like so:
var way = [];
for (var i = 0; i < routes.length; i++) {
way.push(new google.maps.LatLng(parseFloat(routes[i].lat), parseFloat(routes[i].lng)));
}
NB: the use of parseFloat to convert strings like "50.495121" into floating point numbers.

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

Categories