Spring REST JSON Response (original) (raw)
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.

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:
org.springframework.boot
spring-boot-starter-web
This dependency also includes Jackson for JSON conversion.
**pom.xml:
XML `
4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.3 sia GFG-JSON-REST-RESPONSE 0.0.1-SNAPSHOT GFG-JSON-REST-RESPONSE REST API Response <java.version>11</java.version> org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web
<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>
`
**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:
org.projectlombok
lombok
true
**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 |
|---|---|
| @RestController | Combines @Controller and @ResponseBody |
| @RequestMapping | Maps requests to a specific path |
| @CrossOrigin | Allows cross-origin requests |
| @GetMapping | Maps GET request on specific handler method |
| @PathVariable | Binds 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:


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 `
GeeksforGeeksattributeValue will be placed here
attributeValue will be placed here
attributeValue will be placed here
attributeValue will be placed here
`
**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 `
Rest API Response : JSON
| {{json.id}} | {{json.name}} | {{json.data}} |
`
**consume-json.component.css (Style file):
CSS `
h1, tr{ color : green; font-size : 25px; }
`
Add - '' in the 'app.component.html' file
**Output:

Output
**Note: spring-boot-starter-web already includes:
- jackson-databind
- jackson-core
- jackson-annotations
Spring Boot automatically converts Java objects into JSON.