Return JSON Response in Servlet

In this example, we will show simple example about how to return Json response in servlet. The example program has been tested with apache tomcat environment and output are shared in the post.

Project Structure

Return JSON Response in Servlet

Servlet Class (

package com.dineshkrish.service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dineshkrish.pojo.Employee;
import com.dineshkrish.util.JSONConverter;
* @author Dinesh Krishnan
public class EmployeeService extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
// defining the PrintWriter object
PrintWriter out = response.getWriter();
// setting the response type
// creating employee object
Employee employee = new Employee();
// setting the attributes
employee.setEmpName("Dinesh Krishnan");
employee.setEmpQualifcation(new String[]{"MS", "MBA"});
employee.setEmpPhone("+91 8989898989");
// converting object to json using Gson api.

POJO Class (

package com.dineshkrish.pojo;
* @author Dinesh Krishnan
public class Employee {
private int empId;
private String empName;
private int empAge;
private String[] empQualifcation;
private String empEmailId;
private String empPhone;
public int getEmpId() {
return empId;
public void setEmpId(int empId) {
this.empId = empId;
public String getEmpName() {
return empName;
public void setEmpName(String empName) {
this.empName = empName;
public int getEmpAge() {
return empAge;
public void setEmpAge(int empAge) {
this.empAge = empAge;
public String[] getEmpQualifcation() {
return empQualifcation;
public void setEmpQualifcation(String[] empQualifcation) {
this.empQualifcation = empQualifcation;
public String getEmpEmailId() {
return empEmailId;
public void setEmpEmailId(String empEmailId) {
this.empEmailId = empEmailId;
public String getEmpPhone() {
return empPhone;
public void setEmpPhone(String empPhone) {
this.empPhone = empPhone;

Object to JSON Converter (

package com.dineshkrish.util;
* @author Dinesh Krishnan
public class JSONConverter {
private static Gson gson = new Gson();
public static String convert(Object object) {
return gson.toJson(object);

Application Home Page index.html

<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<h1>Service is running...</h1>

Configuration File web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
id="WebApp_ID" version="3.0">

File Output

Return JSON Response in Servlet

Return JSON Response in Servlet


1. Java EE HttpServletRequest Interface
2. Java EE HttpServletResponse Interface
3. Java EE ServletException Class
4. Java IOException Class

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *