Converting java JSONObject to javascript - java

I have a JSONObject I'm sending through AJAX.
JSONObject obj = new JSONObject();
obj.put("nbLike", result);
obj.put("username", "bill");
Then in the success function I want to access the obj properties. eg : username
I'have tried with JSON.parse(obj) but I got an error : Uncaught SyntaxError: Unexpected token '
server side the log shows : {"username":"bill","nbLike":1} //log.info(obj)
client side the log show : ['username':'bill', 'nbLike':1] //console.log(result)
I'd like something like :
console.log("Username : " + obj.username)
Thank you

Convert JSONObject to String before sending it to frontend and add "application/json" to Content-type of your response. Then you can use it as simple js object, don't need to convert it.

Related

AWS API Gateway Integration Response

I am using AWS Lambda and API Gateway and facing an issue with my API's response code,
In case of an exception I am setting responseCode as 400 in my response,
But the API status is 200.
I found that my solution is related to AWS API Gateway's Integration Response,
I created all the possible Http Status codes that my application needs,
And I set the Lambda Error Regex in Integration Response,
But I still get API status as 200 despite me sending "responseCode" : "400", in my APIs response(response type is JsonObject in Java).
I have the following code AWS Lambda code,
I am passing ErrorCode as query parameter to my Get method,
And returning the same Error code in response eg. "responseCode" : "400".
My expected output is "responseCode" : "400" but, the API's status should also become 400 instead of 200.
public class MainHandler implements RequestHandler<JSONObject, JSONObject> {
public JSONObject handleRequest(JSONObject request, Context context) {
try {
JSONObject requestJson = (JSONObject) new JSONParser().parse(request.toString());
System.out.println("RequestJson : " + requestJson);
JSONObject params = (JSONObject) requestJson.get("params");
System.out.println("Params : " + params);
JSONObject queryString = (JSONObject) params.get("querystring");
System.out.println("QueryString : " + queryString);
String error = (String) queryString.get("errorCode");
System.out.println("ErrorCode : " + error);
JSONObject resp = new JSONObject();
resp.put("responseCode", error);
return resp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
AWS API Gateway Method Response -
AWS API Gateway Integration Response -
Postman response -
The API status shows 200 Ok, whereas I want it as 400.
I am referring the following links -
1. https://forums.aws.amazon.com/thread.jspa?threadID=192918
2. Is there a way to change the http status codes returned by Amazon API Gateway?
Your Lambda Error Regex is not a regular expression. Changing it to .*"responseCode":\s"400".* should do it.
But for that use case it would be better to activate Lambda proxy integration. This provides a more flexible way to set the response code directly from the lambda function.

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");

What is the correct way to pass a JSON array to a Neo4j server based java class?

I am hitting a wall trying to get data loaded in a JSON array successfully passed to a java class that runs over the Neo4j server. My intent is to pass a list of entries from the client side to the server - nothing special here. What I am doing is reading the entries on the client side, loading those entries into JSON objects and then putting each JSON object into a JSON array which is then to be passed to the server for further processing.
Here is a section of the client side code that loads the json object and array. NOTE: the below is
just the json related code stripped down w/o the try/catch and other items resident in the code.
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("field1", field1Value1);
jsonObject.put("field2", field2Value1);
jsonObject.put("field3", field3Value1);
jsonArray.put(jsonObject);
JSONObject jsonObject = new JSONObject();
jsonObject.put("field1", field1Value2);
jsonObject.put("field2", field2Value2);
jsonObject.put("field3", field3Value2);
jsonArray.put(jsonObject);
Here is the client side code that handles the http post part of the equation - I believe this is ok.
StringEntity stringEntity = new StringEntity(jsonArray.toString());
stringEntity.setContentType("application/json");
HttpPost post = new HttpPost(
"http://"server":7474/db/data/ext/serverSideClass/graphdb/processJSONData");
post.setEntity(stringEntity);
HTTPPostResponseResults httpResponse = new HTTPPostResponseResults();
httpResponse.checkResponse(post);
Here is the method interface to the server side code and this is where I believe my problem lies. I am thinking the parameter type needs to something other than JSONArray but am not sure what.
#Name("processJSONData")
#Description("process the data passed in.")
#PluginTarget(GraphDatabaseService.class)
public String processJSONData(#Source GraphDatabaseService graphDb,
#Parameter(name = "jsonArray") JSONArray jsonArray) {
And... here is the error being thrown.
"message" : "java.util.ArrayList cannot be cast to java.util.Map",
"exception" : "BadInputException",
"fullname" : "org.neo4j.server.rest.repr.BadInputException",
"stacktrace" : [ "org.neo4j.server.rest.repr.formats.JsonFormat.readMap(JsonFormat.java:92)",
"org.neo4j.server.rest.repr.RepresentationFormat.readParameterList(RepresentationFormat.java:97)",
"org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension
The above should cover it for the items related to this posting. If there is anything needed to clarify this please let me know and I'll provide it. Thank you in advance.

Java : How to handle POST request without form?

I'm sending a http post request from javascript, with some json data.
Javascript
var data = {text : "I neeed to store this string in database"}
var xhr= new XMLHttpRequest();
xhr.open("POST","http://localhost:9000/postJson" , true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(data);
xhr.setRequestHeader("Connection", "close");
//Also, I've tried a jquery POST
//$.post('postJson', {'data=' : JSON.stringify(data)});
//But this doesn't make a request at all. What am I messing up here?
Route
POST /postJson controllers.Application.postJson()
Controller
public static Result postJson(){
//What should I write here to get the data
//I've tried the below but values is showing null
RequestBody rb=request().body();
final Map<String,String[]> values=rb.asFormUrlEncoded();
}
What is the way to parse the POST request body?
Much thanks!
Retreive the request body directly as JSON... no need to complicate your life.
public static Result postJson() {
JsonNode rb = request().body().asJson();
//manipulate the result
String textForDBInsertion = rb.get("text").asText(); //retreives the value for the text key as String
Logger.debug("text for insertion: " + textForDBInsertion
+ "JSON from request: " + rb);
return ok(rb);
}
Also, I recommend you use the AdvancedRestClient Chrome plugin for testing. This way you can eliminate from the equation client-side code errors.
Cheers!

Categories