Return JSON response from Servlet site to Javascript / JSP

I think (actually I KNOW!). I am doing something wrong here. I am trying to populate some values ​​in a HashMap and add each file to the list that will be added to the JSON object:

JSONObject json = new JSONObject(); try { Map address; List addresses = new ArrayList(); int count = 15; for (int i=0 ; i<count ; i++) { address = new HashMap(); address.put("CustomerName" , "Decepticons" + i); address.put("AccountId" , "1999" + i); address.put("SiteId" , "1888" + i); address.put("Number" , "7" + i); address.put("Building" , "StarScream Skyscraper" + i); address.put("Street" , "Devestator Avenue" + i); address.put("City" , "Megatron City" + i); address.put("ZipCode" , "ZZ00 XX1" + i); address.put("Country" , "CyberTron" + i); addresses.add(address); } json.put("Addresses", addresses); } catch (JSONException jse) { } response.setContentType("application/json"); response.getWriter().write(json.toString()); 

My problem is that I know that this returns a string that I cannot parse (this is the problem). My question is how to return the actual encoded JSON string (or even if I do this?) Or the best attack method for this type of problem. The JavaScript I use for this is below:

 function getReadyStateHandler(req) { // Return an anonymous function that listens to the // XMLHttpRequest instance return function () { // If the request status is "complete" if (req.readyState == 4) { // Check that a successful server response was received if (req.status == 200) { msgBox("JSON Response recieved..."); populateDatagrid(req.responseText.toJSON()); } else { // An HTTP problem has occurred alert("HTTP error: " + req.status); } } } } 

Note that the JSON response is returned in order, but its string. Any advice is much appreciated. I also open up the use of googles Gson, but don't have too much knowledge about this.

+7
source share
3 answers

It worked! I had to create a JSONArray from a JSONObject , and then add the array to the final "Addresses" of the JSONObject . Please note the following:

 JSONObject json = new JSONObject(); JSONArray addresses = new JSONArray(); JSONObject address; try { int count = 15; for (int i=0 ; i<count ; i++) { address = new JSONObject(); address.put("CustomerName" , "Decepticons" + i); address.put("AccountId" , "1999" + i); address.put("SiteId" , "1888" + i); address.put("Number" , "7" + i); address.put("Building" , "StarScream Skyscraper" + i); address.put("Street" , "Devestator Avenue" + i); address.put("City" , "Megatron City" + i); address.put("ZipCode" , "ZZ00 XX1" + i); address.put("Country" , "CyberTron" + i); addresses.add(address); } json.put("Addresses", addresses); } catch (JSONException jse) { } response.setContentType("application/json"); response.getWriter().write(json.toString()); 

This worked and returned valid and syntax JSON. Hope this helps someone else in the future. Thanks for the help Marseille

+29
source

I used JSONObject as shown below in Servlet.

  JSONObject jsonReturn = new JSONObject(); NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName); map = new HashMap<String, String>(); map.put("Status", "Success"); map.put("FailureReason", "None"); map.put("DataElements", "2"); jsonReturn = new JSONObject(); jsonReturn.accumulate("Header", map); List<String> list = new ArrayList<String>(); list.add(NhAdminTree); list.add(userName); jsonReturn.accumulate("Elements", list); 

The servlet returns this JSON object, as shown below:

  response.setContentType("application/json"); response.getWriter().write(jsonReturn.toString()); 

This servlet is invoked from a browser using AngularJs, as shown below.

 $scope.GetNeighborhoodTreeUsingPost = function(){ alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName ); $http({ method: 'POST', url : 'http://localhost:8080/EPortal/xlEPortalService', headers: { 'Content-Type': 'application/json' }, data : { 'action': 64, 'userName' : $scope.userName } }).success(function(data, status, headers, config){ alert("DATA.header.status : " + data.Header.Status); alert("DATA.header.FailureReason : " + data.Header.FailureReason); alert("DATA.header.DataElements : " + data.Header.DataElements); alert("DATA.elements : " + data.Elements); }).error(function(data, status, headers, config) { alert(data + " : " + status + " : " + headers + " : " + config); }); }; 

This code worked, and it displays the correct data in the warning dialog:

Data.header.status: Success

Data.header.FailureReason: None

Data.header.DetailElements: 2

Data.Elements: string values ​​separated by coma, i.e. NhAdminTree, username

+2
source

I think what you want to do is turn the JSON string back into an object when it returns to your XMLHttpRequest - right?

If this is the case, you need an eval string to turn it into a JavaScript object - note that this can be dangerous, assuming the JSON string is not malicious and therefore executes it. Preferably you can use jQuery parseJSON

+1
source

All Articles