W3docs

How do you return a JSON object from a Java Servlet

To return a JSON object from a Java Servlet, you can use the following steps:

To return a JSON object from a Java Servlet, you can use the following steps:

  1. Add the following dependencies to your project's classpath:
  • The JSON library of your choice (e.g. Jackson, Gson, etc.)
  • The Servlet API library (e.g. jakarta.servlet-api for modern Jakarta EE, or javax.servlet-api for legacy Java EE)
  1. In your Servlet, use the JSON library to create a JSON object or array. Here is a complete example using Jackson that includes necessary imports, exception handling, and response configuration:
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;

@WebServlet("/json")
public class JsonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode root = mapper.createObjectNode();
        root.put("key", "value");

        response.setContentType("application/json");
        response.getWriter().write(root.toString());
    }
}
  1. Set the response content type to application/json (included in the example above).

  2. Write the JSON object or array to the response using the response.getWriter() method (included in the example above).

That's it! Your Servlet should now return a JSON object in the response.

I hope this helps. Let me know if you have any questions.