How do you return a JSON object from a Java Servlet
How do you return a JSON object form a Java servlet.
Previously when doing AJAX with a servlet I have returned a string. Is there a JSON object type that needs to be used, or do you just return a String that looks like a JSON object eg
String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
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").
Write the JSON object to the response object's output stream.
You should also set the content type as follows, which will specify what you are returning:
response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
out.print(jsonObject);
out.flush();
First convert the JSON object to String
. Then just write it out to the response writer along with content type of application/json
and character encoding of UTF-8.
Here's an example assuming you're using Google Gson to convert a Java object to a JSON string:
protected void doXxx(HttpServletRequest request, HttpServletResponse response) {
// ...
String json = new Gson().toJson(someObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
That's all.