How do you return a JSON object from a Java Servlet
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.
See also:
- How to use Servlets and Ajax?
- What is the correct JSON content type?