[java] 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' }";

This question is related to java json servlets

The answer is


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());
}

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

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:


response.setContentType("text/json");

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

String your_string;

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


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

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


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

{}


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


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!


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.


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

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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to servlets

Google Recaptcha v3 example demo Difference between request.getSession() and request.getSession(true) init-param and context-param java.lang.NoClassDefFoundError: org/json/JSONObject how to fix Cannot call sendRedirect() after the response has been committed? getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? Create a simple Login page using eclipse and mysql Spring get current ApplicationContext insert data into database using servlet and jsp in eclipse What is WEB-INF used for in a Java EE web application?