Send JSON by ajax and get parameters by request in JSP - java

I need to send a JSON object by ajax (with Jquery) and get all parameters by the request Object in JSP (server side).
My JS code is:
var request = new Object();
request.param1= "value1";
request.param2 = "value2";
$.ajax({
type:'GET',
url: 'test.jsp',
//data: {request:JSON.stringify(dataSend)},
//data: {request:dataSend},
//data: JSON.stringify(request),
data:request,
async:true,
success:function(r){
console.log(r);
},
error:function(error){
console.log(error);
}
});
And my JSP code is:
<%#page import="cl.test.pos.web.delegate.POSXXXXXXXX"%>
<%#page import="org.json.simple.JSONObject"%>
<%
JSONObject j = new JSONObject();
if(session.getAttribute("role") != null ){
POSXXXXXXXX bx = new POSXXXXXXXX();
String je;
je = bx.setTest(request);
out.print(je);
out.close();
}else{
j.put("responseStatus","EXCEPTION");
request.getSession().invalidate();
out.print(j);
out.close();
}
%>
And the Method Class is
public String setTest(HttpServletRequest request) throws IOException{
JSONObject j = new JSONObject();
try{
j.putAll(request.getParameterMap());
j.put("responseStatus", "OK");
}catch(FrameworkException e){
/*Any code*/
}catch(Throwable t){
/*Any code*/
}
return j.toJSONString();
}
I Expect return a JSON Object on client and this is so, but, the response is like this:
{"param1":[Ljava.lang.String;#182f12f,"param2":[Ljava.lang.String;#1a881f5}
Values are not understandable and if I send Objects and Arrays, it are so wrong too, for example:
{"parametro4[1][p3]":[Ljava.lang.String;#c5954b,"parametro4[1][p4]":[Ljava.lang.String;#1cc9339,"parametro5[arr1][]":[Ljava.lang.String;#1d5af30}
Please Help me to get All parameters on a JSONObject from HttpServletRequest. I really need to know the best way to do this.
(I already searched in StackOverFlow and the surfing in the web, and I cannot found The best way to do this).

The parameterMap value is an Array Object and not String:
Returns: an immutable java.util.Map containing parameter names as keys
and parameter values as map values. The keys in the parameter map are
of type String. The values in the parameter map are of type String
array.
javadoc for getParameterMao
So you will need to code it, just iterate throught the map and put the parameter name/value in the object.

I already resolved this problem (almost at all), from this way:
public String setTest(HttpServletRequest request) throws IOException{
JSONObject j = new JSONObject();
try{
JsonParser jp = new JsonParser();
Map m = request.getParameterMap();
Gson gi = new Gson();
String stringJson = gi.toJson(m);
j.put("jsonParse",jp.parse(stringJson));
j.put("responseStatus", "OK");
}catch(FrameworkException e){
/*Any code*/
}catch(Throwable t){
/*Any code*/
}
return j.toJSONString();
}
and server response correctly (almost):
{"jsonParse":{"parametro5[arr1][]":["1","2","3"],"pagoAbono":["false"],"parametro4[1][p4]":["3"],"parametro4[1][p3]":["2"],"parametro1":["parametro1"],"parametro4[0][p2]":["1"],"codigoCaja":[""],"parametro5[arr2][1][0][letraX]":["x"],"numeroCheque":[""],"facturasPagos":["195310|234509"],"rutCliente":["154809597"],"banco":[""],"caducidadMes":[""],"parametro4[0][p1]":["0"],"parametro5[arr2][1][]":["x","x"],"numeroTarjeta":[""],"caducidadYear":[""],"montoTotalPago":["334772"],"nombreTitular":[""],"parametro5[arr2][0][]":["a","b","c"],"parametro3[]":["a","b","c"],"parametro2[atributo1]":["atributo1"]},"responseStatus":"OK"}
The only Detail is that the Arrays and Objects are interpreted like the request parameter instead the real Javascript JSONObject.
For example:
If client send this:
var obj = new Object();
obj.param1 = [1,2,3];
Server response this:
obj[param1][0]=1;
obj[param1][1]=2;
obj[param1][2]=3;
Instead to response:
obj.param1[0]=1;
obj.param1[1]=2;
obj.param1[2]=3;
I hope you can understand the problem, and give to me a clue or solution.

Related

Get Value and pass as parameter to function in Java

ResponseEntity<String> respEntity = null;
try {
respEntity = getConfiguredRestTemplate().exchange(uri.toString()
, HttpMethod.GET
, entity
, new ParameterizedTypeReference<String>() {
});
log.debug("URL to retrieve a document : {}", respEntity.getBody());
}
The respEntity.getBody() returns {"url":"https://aps-fst"}
I want to send only the value - https://aps-fst as parameter to a function to download the content in the URL. How to extract only the URL value and pass it as parameter of type URL / String ?
You can use ObjectMapper from jackson and have the response body transformed into a map from which you can take the url value. You can find an example here.
String jsonString = respEntity.getBody();
JSONObject obj = new JSONObject(jsonString);
String s3urlvalue = obj.getString("url");
log.debug("S3 URL to retrieve a document : {} ", s3urlvalue);
I am able to get value with above code

Json object in Map, how to get hold of it in java?

In an XPages application I have in a sessionScope variable the configuration for the application in JSON format.
I wonder how I can get hold of this configuration again in Java?
I tried:
Map<String, Object> sesScope = ExtLibUtil.getSessionScope();
if (null != sesScope.get("configJSON")){
JsonJavaObject jsonObject = new JsonJavaObject();
jsonObject = (JsonJavaObject) sesScope.get("configJSON");
System.out.println("got object?");
System.out.println("json " + jsonObject.toString());
}
In the console I never get to the "got object?" print statement. What am I doing wrong?
The JavaScript method JSON.parse that you use, returns just a plain simple JavaScript object, not the JsonJavaObject. You can't use JavaScript object later in Java without additional unnecessary overhead. Don't use json2.jss, use JsonParser like Paul Withers have told.
Change your code that gets JSON from your Notes field:
#{javascript:
importPackage(com.ibm.commons.util.io.json);
var jsonText = doc.getItemValueString(itemname);
var jsonFactory:JsonFactory = JsonJavaFactory.instanceEx;
var jsonObject = JsonParser.fromJson(jsonFactory, jsonText);
sessionScope.put('configJSON', jsonObject);
}
Modify your provided java code by removing unnecessary line:
Map<String, Object> sesScope = ExtLibUtil.getSessionScope();
if (null != sesScope.get("configJSON")) {
JsonJavaObject jsonObject = (JsonJavaObject) sesScope.get("configJSON");
System.out.println("got object?");
System.out.println("json " + jsonObject.toString());
}
You should now be OK.
Hint: if you use JsonJavaFactory.instance instead of JsonJavaFactory.instanceEx, you'll get java.util.HashMap instead of JsonJavaObject
Has the sessionScope variable been set? Use sesScope.containsKey("configJSON") to verify. If it's an empty JSON object it will be "{}" rather than null. If you're loading as JSON from a REST service or a Notes Document it may be a String rather than a JsonJavaObject. For parsing a String of JSON, you can use com.ibm.commons.util.io.json.JsonParser. The constructor for JsonJavaObject expects a Map, not sure if this is what's being passed in.
JsonJavaObject is your POJO java class ?
If Yes then please use ObjectMapper of Fasterxml to map your JSON data to the fields of JsonJavaObject class.Use this method to map your json data to any POJO class
public final T validateJson(final Map<String, Object> jsonMap, final T temmplateClass) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
try {
// convert JSON string to Map
String jsonString = objectMapper.writeValueAsString(jsonMap);
return objectMapper.readValue(jsonString, (Class<T>) temmplateClass);
} catch (JsonMappingException e) {
throw new NestableRuntimeException(String.format(ApiCommonConstants.INVALID_JSON_FIELD,
e.getPath().get(e.getPath().size() - 1).getFieldName()));
} catch (IOException e) {
throw new NestableRuntimeException(e.getMessage(), e);
}
}

error in parsing JSON in java

I have a response from API that generates authorization token with some other attributes, I'm trying to extract the value of the token from the response which looks like below
{"access_token":"tokenvalue","scope":"somevalue","token_type":"Bearer","expires_in":value}
i tried JSON parse like below:
Myclass response = template.postForObject(url, requestEntity, Myclas.class);
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(response);
String product = (String) jsonObject.get("access_token");
token = response;
}
Recieved error:
parse( ) 
in JSONParser cannot be applied
to
(java.lang.String)
With the line:
String product = (String) jsonObject.get("access_token");
You are trying to get a property called "access_token".
However if you look at your json you will see that there is no property called "access_token".
Perhaps you meant:
String product = (String) jsonObject.get("token");
Like said by Neng Liu before me, this JSON could be incorrect:
{"token":"tokenvalue","scope":"somevalue","token_type":"Bearer","expires_in": value }
Another thing is that JSONObject can receive the JSON format in its constructor JSONObject obj = new JSONObject(response) in your case and then use obj.get("your filed")

How to modify the JSON data and return the updated JSON data

We have a requirement to update the JSON data in middle and need to return the updated JSON data using java. Also it should support any type of JSON data.
ex:
Assume {object:{"color":"red","shape":"Triangle"}} is the JSON data and in this we need to update the shape value to Rectangle and we need to return the updated JSON data as below:
{object:{"color":"red","shape":"Rectangle"}}
For this we need to pass the element path ( which element we need to update) and updateText and JSON Data to the JAVA code.
here is the methodCall:
updateValue("object/shape", "Rectangle", "{object:{"color":"red","shape":"Triangle"}}")
We tried below code using Gson library. But with this code we are able to update the targeted Json element, but the requirement is to return the entire JSON data with the updated value.
So please suggest how do we re-build the JSON data with the updated text.
Below is the code we tried to update the Json Data.
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
String result = "";
for(String key : keys)
{
if (jsonObject.get(key) instanceof JsonObject)
{
jsonObject = (JsonObject)jsonObject.get(key);
}
else if(jsonObject.get(key) instanceof JsonArray)
{
JsonArray jsonArray = (JsonArray)jsonObject.get(key);
result = jsonArray.toString();
}
else
{
result = jsonObject.get(key).toString();
}
}
result = result.replace(result, updateText);
return result;
}
The problem lies in the way you do the replacements. When you translate the JsonObject to String, you lose the object, and after replacement, you just have the replaced String. To fix it, you need to operate directly on the object, instead of the String counterpart. Because JsonObject is mutable, holding a reference to the input will reflect the changes. One drawback is you can't replace a value in a JsonArray this way, partly because you don't know which element to replace. To accomplish that, you will need a little more in the input(either the value to replace or the element position).
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
JsonObject returnVal = jsonObject; // This holds the ref to target json object
JsonPrimitive jp = new JsonPrimitive(updateText);
String finalKey = keys[keys.length - 1];
for(String key : keys)
{
if (jsonObject.get(key).isJsonObject())
{
jsonObject = (JsonObject)jsonObject.get(key);
}
}
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
}
You can use JsonPath lib for that and try using the following code.
private static final Configuration configuration = Configuration.builder()
.jsonProvider(new JacksonJsonNodeJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
JsonNode updatedJson = JsonPath.using(configuration).parse(originaljson)
.set("use the path to go for value", "new value").json();
json = updatedJson.toString();

how to return multiple json objects from java servlet using one ajax request

I am building web application using jsp and servlet, I send ajax request from jsp and I want to return two json objects from servlet. I tried to do the following but the code did not work.
// in jquery I wrote this code
var id = $(this).attr('id');
var paramenters = {"param":id};
$.getJSON("MyServlet", paramenters, function (data1,data2){
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
// in the servlet I wrote this code
String json1 = new Gson().toJson(object1);
String json2 = new Gson().toJson(object2);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json1);
response.getWriter().write(json2);
can someone help me???
You should do it like this:
Server side:
String json1 = new Gson().toJson(object1);
String json2 = new Gson().toJson(object2);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
response.getWriter().write(bothJson);
Client side:
$.getJSON("MyServlet", paramenters, function (data){
var data1=data[0], data2=data[1]; //We get both data1 and data2 from the array
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
Hope this helps. Cheers
Wrap them in JSON array:
[ {..}, {..}, {..}]
or, wrap them in another object:
{ "result1":{..}, "result2":{..} }
You could return a JSON array with both objects as elements of the array. Have your servlet return JSON that has a structure like this one:
[{"name": "object1"}, {"name": "object2"}]
Then your javascript code can be something like this:
$.getJSON("MyServlet", paramenters, function (data){
var data1 = data[0];
var data2 = data[1];
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
you're going to need to put both into a single json string like so
response.getWriter().write("[");
response.getWriter().write(json1);
response.getWriter().write(",");
response.getWriter().write(json2);
response.getWriter().write("]");
this puts them in a json array
you could also put them in a json object
response.getWriter().write("{\"object1\":");
response.getWriter().write(json1);
response.getWriter().write(",\"object2\":");
response.getWriter().write(json2);
response.getWriter().write("}");
#Edgar 's answer works for me. But I think we should avoid to form the array by ourselves, so I suggest to use a list. The codes will be something like this:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
...
resp.setContentType("application/json");
resp.setCharacterEncoding("utf-8");
ArrayList<Object> obj_arr = new ArrayList<Object>();
obj_arr.add(obj1);
obj_arr.add(obj2);
Gson gson = new Gson();
String tmp = gson.toJson(obj_arr);
resp.getWriter().write(tmp);
}
And in the front end, for the data we get, we can use data[0] to retrive obj1 and data[1] to retrive obj2. The codes will be something like this (I am using ajax here):
$('#facts_form').submit(function (e) {
e.preventDefault();
var data = new FormData(this);
var url = 'import';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false,
async: false,
cache: false,
success: function (data) {
for (var i = 1; i < data.length; i++){
//do whatever
}
},
error: function (xhr, status, error) {
alert(status + "\n" + error);
}
});
});

Categories