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:
- 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-apifor modern Jakarta EE, orjavax.servlet-apifor legacy Java EE)
- 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());
}
}-
Set the response content type to
application/json(included in the example above). -
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.