How to Return a JSON Object from a Java Servlet

How do you return a JSON object from a Java Servlet

I do exactly what you suggest (return a String).

You might consider setting the MIME type to indicate you're returning JSON, though (according to this other stackoverflow post it's "application/json").

Getting data from incoming JSON in a Java servlet

I think the client send JSON data to you in the body of the request, not in a parameter. So the parameter that you try to parse as JSON data will be always null. To accomplish your task, you have first of all to get the body request and then parse it as JSON. For example, you can convert the body into a String with a method like this:

public static String getBody(HttpServletRequest request)  {

String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;

try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
// throw ex;
return "";
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {

}
}
}

body = stringBuilder.toString();
return body;
}

So, your method will become:

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) {
// this parses the incoming JSON from the body.
JSONObject jObj = new JSONObject(getBody(request));

Iterator<String> it = jObj.keys();

while(it.hasNext())
{
String key = it.next(); // get key
Object o = jObj.get(key); // get value
System.out.println(key + " : " + o); // print the key and value
}
...

Returning JSON object as response in Spring Boot

As you are using Spring Boot web, Jackson dependency is implicit and we do not have to define explicitly. You can check for Jackson dependency in your pom.xml in the dependency hierarchy tab if using eclipse.

And as you have annotated with @RestController there is no need to do explicit json conversion. Just return a POJO and jackson serializer will take care of converting to json. It is equivalent to using @ResponseBody when used with @Controller. Rather than placing @ResponseBody on every controller method we place @RestController instead of vanilla @Controller and @ResponseBody by default is applied on all resources in that controller.
Refer this link: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

The problem you are facing is because the returned object(JSONObject) does not have getter for certain properties. And your intention is not to serialize this JSONObject but instead to serialize a POJO. So just return the POJO.

Refer this link: https://stackoverflow.com/a/35822500/5039001

If you want to return a json serialized string then just return the string. Spring will use StringHttpMessageConverter instead of JSON converter in this case.

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

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

Return JSON from servlet

IE caches AJAX requests aggressively (more than Firefox, Chrome, and Safari, anyway).
Sometimes you need to set cache header controller when request. Like cache:false. I tried to fix your code like this

request.setCharacterEncoding("utf8");
//response.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
System.out.println(jsonObj.get("message"));
JSONObject obj = new JSONObject();
obj.put("message", "hello from server");
out.print(obj.toString());

I changed your response content-type from application/json; charset=utf8 to just application/json and that worked.

Returning JSON response from Servlet to Javascript/JSP page

Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe 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 parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel



Related Topics



Leave a reply



Submit