Java servlet JSON tutorial

Java servlet JSON tutorial shows how to return JSON data from a Java servlet. We use Gson library to work with JSON data format. The web application is deployed on Tomcat server.

Apache Tomcat is an open source Java Servlet Container developed by the Apache Software Foundation (ASF). It is the most popular Java web server. Gson is an open source Java library to serialize and deserialize Java objects to (and from) JSON.

Java Servlet

Servlet is a Java class which responds to a particular type of network request - most commonly an HTTP request. Java servlets are used to create web applications. They run in servlet containers such as Tomcat or Jetty. Modern-day Java web development uses frameworks that are built on top of servlets.


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json. The JSON filename extension is .json.

Java servlet JSON application

The following web application uses a Java servlet to send data (list of cities) to the client in JSON format.

$ tree
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           ├── bean
    │   │           │   └──
    │   │           ├── service
    │   │           │   └──
    │   │           └── web
    │   │               └──
    │   └── webapp
    │       └── META-INF
    │           └── context.xml
    └── test
        └── java

This is the project structure.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" 







This is the Maven POM file. We have two artifacts: javax.servlet-api for servlets and gson for JSON processing in Java. The maven-war-plugin is responsible for collecting all artifact dependencies, classes and resources of the web application and packaging them into a web application archive (WAR).

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/ServletJson"/>

In the Tomcat context.xml file, we define the context path. It is the name of the web application.
package com.zetcode.bean;

public class City {

    private Long id;
    private String name;
    private int population;

    public City() {

    public City(Long id, String name, int population) { = id; = name;
        this.population = population;

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getPopulation() {
        return population;

    public void setPopulation(int population) {
        this.population = population;

    public String toString() {
        return "City{" + "id=" + id + ", name=" + name + 
                ", population=" + population + '}';

This is the City bean. It has three attributes: id, name, and population.
package com.zetcode.web;

import com.zetcode.bean.City;
import com.zetcode.service.CityService;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "GetCities", urlPatterns = {"/GetCities"})
public class GetCities extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        try (PrintWriter out = response.getWriter()) {

            List<City> cities = CityService.getCities();

            out.print(new Gson().toJson(cities));

This is the GetCities servlet. It retrieves data from a service class and returns them to the client in JSON format.


We set the content type of the response object to application/json.

try (PrintWriter out = response.getWriter()) {

We get the PrintWriter which is used to send character text to the client.

List<City> cities = CityService.getCities();

From the CityService, we get the list of cities.

out.print(new Gson().toJson(cities));

We use the Gson library to transform a Java list into JSON array. The array is written to the writer. The array was not given a name.
package com.zetcode.service;

import com.zetcode.bean.City;
import java.util.ArrayList;
import java.util.List;

public class CityService {

    public static List<City> getCities() {

        List<City> cities = new ArrayList<>();
        cities.add(new City(1L, "Bratislava", 432000));
        cities.add(new City(2L, "Budapest", 1759000));
        cities.add(new City(3L, "Prague", 1280000));
        cities.add(new City(4L, "Warsaw", 1748000));
        cities.add(new City(5L, "Los Angeles", 3971000));
        cities.add(new City(6L, "New York", 8550000));
        cities.add(new City(7L, "Edinburgh", 464000));
        cities.add(new City(8L, "Berlin", 3671000));
        return cities;

The CityService's getCities() method returns a list of city objects.

Creating a request with curl

The curl is a tool to transfer data from or to a server, using one of the supported protocols.

$ curl localhost:8084/ServletJson/GetCities
{"id":5,"name":"Los Angeles","population":3971000},{"id":6,"name":"New York","population":8550000},

This is the output. With the curl command, we issue a HTTP GET request to the GetCities servlet.

Naming the JSON array

In case we wanted to name the returned JSON array, we can use the following code:

Gson gson = new GsonBuilder().create();
JsonArray jarray = gson.toJsonTree(cities).getAsJsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.add("cities", jarray);


In the servlet, we place the JSON array into another JSON object and name the property cities.

In this tutorial, we have sent JSON data from a Java servlet.

You might also be interested in the following related tutorials: Java Servlet PDF tutorial, Java RequestDispatcher, Serving plain text from Java servlet, Java servlet check box tutorial, Java servlet image tutorial, Java Servlet HTTP headers, or Java tutorial