Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 e.g.

String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
like image 757
Ankur Avatar asked Jan 06 '10 04:01

Ankur


People also ask

Can servlet return JSON?

To send a JSON response from the Servlet we first need to convert the Employee object into its JSON representation. There are many java libraries available to convert an object to there JSON representation and vice versa. Most prominent of them would be the Gson and Jackson libraries.

How do you create and return a JSON object in Java?

getJSONArray("result"); final JSONObject jsonObject = result. getJSONObject(0); return jsonObject. getString("firstName"); } catch (ClientProtocolException e) { // TODO Auto-generated catch block ....

How do I return a JSON response?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.


5 Answers

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();
like image 172
user241924 Avatar answered Sep 29 '22 20:09

user241924


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?
like image 40
BalusC Avatar answered Sep 29 '22 19:09

BalusC


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").

like image 21
Mark Elliot Avatar answered Sep 29 '22 18:09

Mark Elliot


How do you return a JSON object from a Java Servlet

response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();

  //create Json Object
  JsonObject json = new JsonObject();

    // put some value pairs into the JSON object .
    json.addProperty("Mobile", 9999988888);
    json.addProperty("Name", "ManojSarnaik");

    // finally output the json string       
    out.print(json.toString());
like image 45
MAnoj Sarnaik Avatar answered Sep 29 '22 19:09

MAnoj Sarnaik


I used Jackson to convert Java Object to JSON string and send as follows.

PrintWriter out = response.getWriter();
ObjectMapper objectMapper= new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(MyObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(jsonString);
out.flush();
like image 29
ravthiru Avatar answered Sep 29 '22 18:09

ravthiru