160

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' }";
rodrigo-silveira
  • 10,557
  • 9
  • 55
  • 98
Ankur
  • 47,089
  • 107
  • 237
  • 309
  • 10
    Nitpick; shouldn't you want more like `{ key1: value1, key2: value2 }`? –  Jan 06 '10 at 04:44
  • 14
    Nitpick: what he really wants is { "key1": "value1", "key2": "value2" }... :-) – PhiLho Oct 12 '11 at 09:10
  • @Ankur checkout the [link](http://stackoverflow.com/questions/16909742/spring-3-2-0-web-mvc-rest-api-and-json-2-post-requests-how-to-get-it-right-on) if you decided to use Spring 3.2.0. – AmirHd Jun 05 '13 at 11:10
  • 5
    Nitpick: we shouldn't assume the values are Strings, so what he really wants is { "key1": value1, "key2": value2 } – NoBrainer Feb 09 '16 at 22:10
  • These Nitpicks (esp. in this order), are epic :) – Ankur Jun 23 '19 at 22:48

13 Answers13

178

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();
Symmetric
  • 3,755
  • 5
  • 29
  • 48
user241924
  • 4,100
  • 7
  • 25
  • 25
  • 7
    This helped me. As mentioned in Mark Elliot answer, **jsonObject** could be just a string formatted as a json. Remember to use double quotes, as single quotes won't give you a valid json. Ex.: `String jsonStr = "{\"my_key\": \"my_value\"}";` – marcelocra Feb 23 '14 at 01:53
  • 3
    It will be good to use response.setCharacterEncoding("utf-8"); too – erhun Apr 09 '15 at 14:25
83

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:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • I'm doing this to send response to javascript and displaying the response in alert. why is it displaying the html code inside the alert..why am i getting the html code as response. i did the exact same thing like you said. – Abhi Mar 11 '16 at 04:21
  • I have the same issue as @iLive – Wax Apr 21 '17 at 00:08
58

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

Community
  • 1
  • 1
Mark Elliot
  • 68,728
  • 18
  • 135
  • 157
30

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());
MAnoj Sarnaik
  • 1,452
  • 15
  • 15
9

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();
ravthiru
  • 6,418
  • 2
  • 31
  • 44
8

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

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

{}

superUser
  • 982
  • 11
  • 9
7

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.

informatik01
  • 15,174
  • 9
  • 67
  • 100
nil
  • 3,096
  • 1
  • 19
  • 20
  • Incorrect. There is usually no reason to add overhead of constructing a `String` -- output should go straight to `OutputStream`. Or, if intermediate form is needed for some reason, can use `byte[]`. Most Java JSON libraries can write directly to `OutputStream`. – StaxMan Oct 14 '13 at 17:04
7

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());
}
Rafael Barros
  • 904
  • 14
  • 24
3

response.setContentType("text/json");

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

String your_string;

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

Ian Purton
  • 13,711
  • 2
  • 25
  • 23
RHT
  • 4,742
  • 2
  • 23
  • 32
  • do I need to use getBytes("UTF-8")) or can I just return the String variable? – Ankur Jan 06 '10 at 07:24
  • It's a safe programming practice to use UTF-8 for encoding the response of a web application. – RHT Jan 06 '10 at 21:36
1

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

Enamul Haque
  • 3,249
  • 1
  • 20
  • 32
0

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!

clemens
  • 14,173
  • 11
  • 38
  • 52
0

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

xrcwrn
  • 4,867
  • 17
  • 58
  • 117