Servlet doesnt write JSON Output to AJAX - json

Following code for my output:
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
ToJson obj = new ToJson();
String obj1 = objectMapper.writeValueAsString(obj);
response.setContentType("application/json");
out.print(obj1);
System.out.println(obj1);
out.close();
The obj1 looks like this: {"prname1":"P1neu","anz1":"342356","prid1":"1","price1":"25"}
It should send the string out so I can parse it in my AJAX and display it but somwhow it ends up with nothing as console.log/etc doesnt display any data.
I had out.append but it also didnt work.

Use below code to send response as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(obj1);
Please check this How to use Servlets and Ajax?
It will surely help you.

Related

Posting Json as Entity with scalaj-http

the api of scalaj-http is clean and I would like to use it for a new project, but it usually post a Json in StringEntity as parameter, like this
JSONObject TokenRequest = new JSONObject()
.put("Credentials", new JSONObject()
.put("Username", username)
.put("Password", password));
StringEntity requestBody = new StringEntity(TokenRequest.toString());
httppost.setEntity(requestBody);
Not sure if it doable with scalaj-http?
According to their github page you need to set the content-type header to application/json to send the body as json.
Http(url).postData(data).header("content-type", "application/json").asString.code

Use a JSON with JSONOBJECT in Java

I want to use the following JSON in my code in Java:
[
{
"speed": 200
}
]
I tried to write this line :
JSONObject jsonBody = new JSONObject("[{\"speed\": 200}]");
But I always get an error. What is the exact format that I have to use here??
EDIT: So it would be more proper to use a JSONArray rather than use a JSONObject (as my last post said)
So the correct java code would be
String json = "[{\"speed\": 200}]";
System.out.println(json);
JSONArray jsonBody = new JSONArray(json);
System.out.println(jsonBody.getJSONObject(0).get("speed"));

Format JSON String in JSP

I have started working on JSON, I am returning a JSON from JSP through AJAX call. Its working well.
only i need to change the format of my returning JSON String.
Following is the String what my JSP is returing.
[{"VV":0,"desc":"XXXXXXX","amount":0,"date":"12/03/2013","watch":""},{"VV":1,"desc":"XXXXXXX","amount":1,"date":"12/03/2013","watch":""}]
and Below is the String what I want my JSP to return.
{"total":"2","rows":[{"VV":0,"desc":"XXXXXXX","amount":0,"date":"12/03/2013","watch":""},{"VV":1,"desc":"XXXXXXX","amount":1,"date":"12/03/2013","watch":""}] }
Can Any one please help.
Following code I am using to send the output back to front end.
JSONArray arrayObj=new JSONArray();
JSONObject json = new JSONObject();
json.put("VV", i);
json.put("desc", "XXXXXXXXX");
json.put("amount", 1);
json.put("date", "12/03/2013");
json.put("watch", "");
PrintWriter out1 = response.getWriter();
out1.println(arrayObj);
What you need to so with the "json" object that you have created is to allocate to a new variable. Something like this:
arrayObj.put(json);
Next you need to create another object:
JSONObject finalObj = new JSONObject();
finalObj.put("total", 2);
finalObj.put("rows",arrayObj);
finalObj.flush();
I think you need to convert it to String and override the toString() method according to your needs and pass it to your JSP page

JSON response from ektorp / couchdb

For client requests to ektorp / couchdb I would like to pass JSON back to the client.
(Why not use couchdb direktly? Because I have to do some tweeks to the data on a Java layer inbetween.)
So is there for example a way to get JSON data from a CouchDbRepositorySupport queryView?
As far as I know, from consulting the documentation the following should do it
ViewResult result = db.queryView(query);
for (ViewResult.Row row : result) {
JsonNode docNode = row.getDocAsNode();
}
Here's another way:
InputStream is = db.queryForStream(query);
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(is);
(JsonNode and ObjectMapper are from the org.codehaus.jackson library.)

JSON, Servlet, JSP

Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).
Can I pass the parameters from the database?
Once the URL is entered, the information returned will be in text format using JSON
format.
The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}
How shall I do this in servlets? doPost()
Just set the proper content type and encoding and write the JSON string to the response accordingly.
String json = "{\"status\": \"Yes\"}";
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of composing the JSON yourself, you may consider using an existing JSON library to ease the job of JSON (de)serializing in Java. For example Google Gson.
Map<String, String> result = new HashMap<String, String>();
result.put("status", "Yes");
// ... (put more if necessary)
String json = new Gson().toJson(result);
// ... (just write to response as above)
Jackson is another option for JSON object marshalling.