161
votes

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' }";
13
Nitpick; shouldn't you want more like { key1: value1, key2: value2 }?user240438
Nitpick: what he really wants is { "key1": "value1", "key2": "value2" }... :-)PhiLho
@Ankur checkout the link if you decided to use Spring 3.2.0.AmirHd
Nitpick: we shouldn't assume the values are Strings, so what he really wants is { "key1": value1, "key2": value2 }NoBrainer
These Nitpicks (esp. in this order), are epic :)Ankur

13 Answers

178
votes

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();
84
votes

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:

59
votes

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

31
votes

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());
9
votes

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();
8
votes

Just write a string to the output stream. You might set the MIME-type to text/javascript (edit: application/json is apparently officialer) if you're feeling helpful. (There's a small but nonzero chance that it'll keep something from messing it up someday, and it's a good practice.)

8
votes

Gson is very usefull for this. easier even. here is my example:

public class Bean {
private String nombre="juan";
private String apellido="machado";
private List<InnerBean> datosCriticos;

class InnerBean
{
    private int edad=12;

}
public Bean() {
    datosCriticos = new ArrayList<>();
    datosCriticos.add(new InnerBean());
}

}

    Bean bean = new Bean();
    Gson gson = new Gson();
    String json =gson.toJson(bean);

out.print(json);

{"nombre":"juan","apellido":"machado","datosCriticos":[{"edad":12}]}

Have to say people if yours vars are empty when using gson it wont build the json for you.Just the

{}

7
votes

There might be a JSON object for Java coding convenience. But at last the data structure will be serialized to string. Setting a proper MIME type would be nice.

I'd suggest JSON Java from json.org.

7
votes

Depending on the Java version (or JDK, SDK, JRE... i dunno, im new to the Java ecosystem), the JsonObject is abstract. So, this is a new implementation:

import javax.json.Json;
import javax.json.JsonObject;

...

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

    JsonObject json = Json.createObjectBuilder().add("foo", "bar").build();

    out.print(json.toString());
}
3
votes

response.setContentType("text/json");

//create the JSON string, I suggest using some framework.

String your_string;

out.write(your_string.getBytes("UTF-8"));

1
votes

You may use bellow like.

If you want use json array:

  1. download json-simple-1.1.1.jar & add to your project class path
  2. Create A class named Model like bellow

    public class Model {
    
     private String id = "";
     private String name = "";
    
     //getter sertter here
    }
    
  3. In sevlet getMethod you can use like bellow

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
      //begin get data from databse or other source
      List<Model> list = new ArrayList<>();
      Model model = new Model();
      model.setId("101");
      model.setName("Enamul Haque");
      list.add(model);
    
      Model model1 = new Model();
      model1.setId("102");
      model1.setName("Md Mohsin");
      list.add(model1);
      //End get data from databse or other source
    try {
    
        JSONArray ja = new JSONArray();
        for (Model m : list) {
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("id", m.getId());
            jSONObject.put("name", m.getName());
            ja.add(jSONObject);
        }
        System.out.println(" json ja = " + ja);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(ja.toString());
        response.getWriter().flush();
       } catch (Exception e) {
         e.printStackTrace();
      }
    
     }
    
  4. Output:

        [{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
    

I you want json Object just use like:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        JSONObject json = new JSONObject();
        json.put("id", "108");
        json.put("name", "Enamul Haque");
        System.out.println(" json JSONObject= " + json);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        // System.out.println("Response Completed... ");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Above function Output:

{"name":"Enamul Haque","id":"108"}

Full source is given to GitHub: https://github.com/enamul95/ServeletJson.git

0
votes

Close to BalusC answer in 4 simple lines using Google Gson lib. Add this lines to the servlet method:

User objToSerialize = new User("Bill", "Gates");    
ServletOutputStream outputStream = response.getOutputStream();

response.setContentType("application/json;charset=UTF-8");
outputStream.print(new Gson().toJson(objToSerialize));

Good luck!

0
votes

By Using Gson you can send json response see below code

You can see this code

@WebServlet(urlPatterns = {"/jsonResponse"})
public class JsonResponse extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
    Subject subject1 = new Subject(1, "Computer Fundamentals");
    Subject subject2 = new Subject(2, "Computer Graphics");
    Subject subject3 = new Subject(3, "Data Structures");
    Set subjects = new HashSet();
    subjects.add(subject1);
    subjects.add(subject2);
    subjects.add(subject3);
    student.setSubjects(subjects);
    Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
    student.setAddress(address);
    Gson gson = new Gson();
    String jsonData = gson.toJson(student);
    PrintWriter out = response.getWriter();
    try {
        out.println(jsonData);
    } finally {
        out.close();
    }

  }
}

helpful from json response from servlet in java