Spring - REST JSON Response

Last Updated : 22 Jan, 2026

In Spring, a REST JSON response is used to send data from the server to the client in JSON (JavaScript Object Notation) format. Spring simplifies this process by automatically converting Java objects into JSON using Jackson when building RESTful web services.

The diagram illustrates how a client communicates with a Spring REST API by sending requests and receiving JSON responses.

SpringRESTJSONResponse

Prerequisites

The prerequisites required are as follows: 

  • Basic knowledge of Spring Boot and REST APIs.
  • A Spring Boot project set up with Maven or Gradle.
  • Familiarity with JSON and its structure.

JSON

JSON stands for JavaScript Object Notation. It is a text-based data format used to exchange data between a server and a client. Although derived from JavaScript syntax, JSON is language-independent and supported by most programming languages.

Example: JSON Object

{
"id": 07,
"framework": "Spring",
"API": "REST API",
"Response JSON": true
}

Example: JSON Array

[
{
"id": 07,
"name": "darshan"
},
{
"id": 08,
"name": "geek"
}
]

Setting Up the Spring Boot Project

Step 1: Project Structure

The project structure for the application is as follow:


Step 2: Verify pom.xml

Spring Initializr automatically adds required dependencies. Make sure spring-boot-starter-web is present:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

This dependency also includes Jackson for JSON conversion.

pom.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>sia</groupId>
    <artifactId>GFG-JSON-REST-RESPONSE</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GFG-JSON-REST-RESPONSE</name>
    <description>REST API Response</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Step 3: Bootstrapping the Spring Application

Create the main application class to bootstrap the Spring Boot application.

GfgJsonRestResponseApplication.java:

Java
package gfg;
// Importing classes
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

// Annotation
@SpringBootApplication

// Main class
public class GfgJsonRestResponseApplication {
    public static void main(String[] args)
    {
        SpringApplication.run(
            GfgJsonRestResponseApplication.class, args);
    }
}

Step 4: Creating the Domain Bean

The domain bean defines the structure of the JSON response.

Steps

  • Create a class DomainBean
  • Use Lombok to automatically generate getters and setters.

Maven Dependency:

Dependency is as depicted below as follows:

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

DomainBean.java:

Java
package gfg;

// Importing class
import lombok.Data;

// Annotation
@Data
// Class
public class DomainBean {

    String id;
    String name;
    String data;
}

Spring automatically converts this Java object into JSON.

Step 5: Implementing the REST Controller

The REST controller handles incoming requests and sends JSON responses. Key annotations used include @RestController, @RequestMapping, and @GetMapping.

Important Annotations Used

Annotation

Description

@RestControllerCombines @Controller and @ResponseBody
@RequestMappingMaps requests to a specific path
@CrossOriginAllows cross-origin requests
@GetMappingMaps GET request on specific handler method
@PathVariableBinds URI values to method parameters

RestJsonResponse.java:

This class provides RESTful services.

Java
package gfg;

import java.util.ArrayList;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path="/JSON", produces="application/json")
@CrossOrigin(origins="*") 
public class RestJsonResponse {

    @GetMapping("/data")
    public ArrayList<DomainBean> get() {
        
        ArrayList<DomainBean> arr = new ArrayList<>();
        
        DomainBean userOne = new DomainBean();
        userOne.setId("1");
        userOne.setName("@geek");
        userOne.setData("GeeksforGeeks");
        
        DomainBean userTwo = new DomainBean();
        userTwo.setId("2");
        userTwo.setName("@drash");
        userTwo.setData("Darshan.G.Pawar");
        
        arr.add(userOne);
        arr.add(userTwo);
        
        return arr;
    }
    
    @GetMapping("/{id}/{name}/{data}")
    public ResponseEntity<DomainBean> getData(@PathVariable("id") String id, 
                             @PathVariable("name") String name, 
                                @PathVariable("data") String data) {
        
        DomainBean user = new DomainBean();
        user.setId(id);
        user.setName(name);
        user.setData(data);
        
        HttpHeaders headers = new HttpHeaders();
        
        ResponseEntity<DomainBean> entity = new ResponseEntity<>(user,headers,HttpStatus.CREATED);
        
        return entity;
    }
}

Outputs:

An-array-of-JSON-object-literals
JSON-object-literal

REST API's JSON response can be consumed by:

  • Spring application itself.
  • Front-end application/framework

Consuming REST API in a Spring Application

Spring provides RestTemplate for consuming REST APIs.

ConsumeResponse.java ( Consume REST API response ):

Java
// Java Program to Illustrate Consume REST API response
package gfg;

// Importing required classes
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

// Class
public class ConsumeResponse {

    // Creating an object of ResponseEntity class
    RestTemplate rest = new RestTemplate();

    public ResponseEntity<DomainBean> get()
    {

        return rest.getForEntity(
            "http://localhost:8080/JSON/{id}/{name}/{data}",
            DomainBean.class, "007", "geek@drash",
            "Darshan.G.Pawar");
    }
}

A normal Spring controller is used to retrieve the responses from the RestTemplate method and returns a view.

Displaying Response Using Thymeleaf

ResponseController.java ( Regular Controller ):

Java
// Java Program to Illustrate Regular Controller

package gfg;

// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

// Annotation
@Controller
@RequestMapping("/ConsumeResponse")

// Class
public class ResponseController {

	@GetMapping("/get") public String get(Model model)
	{

		// Creating object of ConsumeResponse class
		ConsumeResponse data = new ConsumeResponse();
		model.addAttribute("response",
						data.get().getBody());
		model.addAttribute("headers",
						data.get().getHeaders());

		return "output";
	}
}

 Output.html (output of API: Thymeleaf template):

HTML
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml/"
      xmlns:th="https://www.thymeleaf.org/">
<head>
<title>GeeksforGeeks</title>
</head>
<body>

<h1 style="color:forestgreen" th:text="${response.id}">attributeValue will be placed here</h1>
<h1 style="color:forestgreen" th:text="${response.name}">attributeValue will be placed here</h1> 
<h1 style="color:forestgreen" th:text="${response.data}">attributeValue will be placed here</h1>

<h2 style="color:forestgreen; width : 350px" th:text="${headers}">attributeValue will be placed here</h2>

</body>
</html>

Output:

Output

Front-end Application/Framework - Angular

consume-json.component.ts (Angular component):

  • This component retrieves the JSON data from the specified URL targeting REST API.
  • Retrieved data is stored in a variable.

import { Component, OnInit, Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Component({

selector: 'app-consume-json',

templateUrl: './consume-json.component.html',

styleUrls: ['./consume-json.component.css']

})

export class ConsumeJsonComponent implements OnInit {

restData : any;

constructor(private http:HttpClient) { }

ngOnInit() {

this.http.get('http://localhost:8080/JSON/data')

.subscribe(data => this.restData = data);

}

}

consume-json.component.html (view of component):

  • Get the stored data by dot( . ) notation.
  • 'ngFor' is an Angular template directive used for iterating through the collection of objects.
HTML
<h1>Rest API Response : JSON</h1>

<div>
 <table *ngFor="let json of restData">
   <tr>
     <td>{{json.id}}</td>
     <td>{{json.name}}</td>
     <td>{{json.data}}</td>
   </tr>
 </table>
</div>

consume-json.component.css (Style file):

CSS
h1, tr{ 
  color : green; 
  font-size : 25px; 
}

Add - '<app-consume-json></app-consume-json>' in the 'app.component.html' file

Output:

Output
Output

Note: spring-boot-starter-web already includes:

  • jackson-databind
  • jackson-core
  • jackson-annotations

Spring Boot automatically converts Java objects into JSON.

    Comment

    Explore