The Wayback Machine - https://web.archive.org/web/20240713082030/https://www.geeksforgeeks.org/spring-rest-json-response/
Open In App

Spring – REST JSON Response

Last Updated : 03 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

REST APIs are becoming popular for the advantages they provide in the development of applications. REST APIs work like a client-server architecture. The client makes a request and a server (REST API) responds back by providing some kind of data. A client can be any front-end framework like Angular, React, etc, or Spring application ( internal/external ) itself. Data can be sent in various formats like plain text, XML, JSON, etc. Of these formats, JSON ( JavaScript Object Notation ) is a standard for transporting data between web applications.

Spring Application

Pre-requisites required are as follows: 

  1. JSON string can be stored in it own file with the ‘.json‘ extension.
  2. It has the MIME type of – ‘application/json‘.

JSON

JSON is an abbreviation for JavaScript Object Notation. It is a text-based data format following Javascript object syntax. It has syntax somewhat like a Javascript object literal and can be used independently from Javascript. Many programming environments have the ability to parse and generate JSON. It exists as a string and needs to be converted into a native Javascript object to access the data by available global JSON methods of Javascript.

Structure of the JSON

{
  "id" : 07,
  "framework" : "Spring",
  "API" : "REST API",
  "Response JSON" : true
}
On sending an array of objects, they are wrapped in the square brackets

[
 {
  "id" : 07,
  "name" : "darshan"
 },
 {
  "id" : 08,
  "name" : "DARSHAN"
 }
]
  • Spring framework’s ‘Starter Web’ dependency provides you with the two essential features of Spring MVC – (Spring’s web framework)  and the RESTful ( REST API ) methodology.
  • To include ‘Starter Web’ in the Spring application, add the following dependency –
Maven -> pom.xml

 <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

Project structure – Maven

File: pom.xml (Configurations)

XML




<?xml version="1.0" encoding="UTF-8"?>
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    <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>


File: GfgJsonRestResponseApplication.java ( Bootstrapping of the application )

Java




// Java Program to Illustrate Bootstrapping of an
// Application
 
package gfg;
 
// Importing classes
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
// Annotation
@SpringBootApplication
 
// Main class
public class GfgJsonRestResponseApplication {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        SpringApplication.run(
            GfgJsonRestResponseApplication.class, args);
    }
}


 
 

File: DomainBean.java ( User properties – The data to be transferred ) 

 

  • Java Beans requires the Getter/Setter methods.
  • One can generate them automatically with the ‘@Data’ annotation of the ‘Lombok’ library.
  • Dependency is as depicted below as follows:
Maven -> pom.xml

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

 

Java




// java Program to illustrate DomainBean class
 
package gfg;
 
// Importing class
import lombok.Data;
 
// Annotation
@Data
// Class
public class DomainBean {
 
    String id;
    String name;
    String data;
}


 
 

File: RestJsonResponse.java ( REST API )

 

  • This class provides RESTful services.
  • Essential annotations are –

Annotation

Description

@RestController Combines @Controller and @ResponseBody
@RequestMapping Maps web requests with ‘path’ attribute and response format with ‘produces’ attribute
@CrossOrigin Permits cross-origin web requests on the specific handler classes/methods
@GetMapping Maps GET request on specific handler method
@PathVariable Binds the URI template variables to method parameters

 

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:

  1. Spring application itself.
  2. Front-end application/framework

A: Spring Application

  • Spring offers the ‘RestTemplate‘ – a convenient way of handling a REST response.
  • It has the HTTP method-specific handler methods.

File: 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");
    }
}


 
 

File: ResponseController.java ( Regular Controller )

 

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

 

Example:

 

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";
    }
}


 
 

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

 

HTML




<!DOCTYPE html>
      xmlns:th="http://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:

Response with JSON as content type

B: Front-end Application/Framework – Angular

File: 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);
  }
}

File: 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>


File: 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:

 

Response retrieved by Angular component

  • You can additionally map an object to JSON object literal using the Jackson API.
  • Add the following dependency:
Maven -> pom.xml
        
<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.5.3</version>
</dependency>

 

Note: This dependency will also automatically add the following libraries to the classpath:

 

  • jackson-annotations
  • jackson-core

 



Previous Article
Next Article

Similar Reads

Spring - REST XML Response
The popularity of REST API is increasing day by day as it fulfills architecting an application in a convenient manner. A REST API is an acronym for 'Representational state transfer'. It is also called RESTful web services. It is also a 'Controller', but with a difference that Rest Controller returns Data, while Controller returns a View of 'Model-V
7 min read
Spring REST - Response for Access Denied Request
The Access Denied Request has an error code of 403. This is the error that is generated when the user tries to access certain resources that he is not authorized. The system displays a whitelabel error displaying the status code 403. In this article, let us regenerate this error using spring security and then handle the same effectively using sprin
5 min read
JSON using Jackson in REST API Implementation with Spring Boot
Whenever we are implementing a REST API with Spring (Spring Boot), we would have come across the requirement to exclude NULLs in the JSON Response of the API. Also, there might be a requirement to externalize turning ON/OFF this feature: Exclude NULLS in the JSON Response, thereby allowing the consumer of the API to customize as per the need. In th
3 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
How to read Array of Nested JSON Response in Postman ?
We know that the postman is the one who delivers the letters sent by your friends, colleagues, or relatives and acts as a bridge of communication. Here Postman refers to the development of API that acts as a bridge or communication between different programs. In other words, it is an API client, made for developing, testing, and management. You can
3 min read
How to Check if the Response of a Fetch is a JSON Object in JavaScript?
In JavaScript, when making HTTP requests using the Fetch API, it's common to expect JSON data as a response from the server. However, before working with the response data, it's essential to verify whether it is indeed a JSON object or not. The below approaches can help you to check if the response is in JSON format or not: Table of Content By usin
2 min read
How to Send JSON Response using Node.js ?
NodeJS is the runtime environment, which can execute the javascript code on any platform. It is widely used to create and run web application servers because of its salient features. During production, several times we need to send the resources or some type of information as a response, and javascript object notation (JSON) syntax is widely used t
5 min read
Spring Boot - Service Class Example for Displaying Response Codes and Custom Error Codes
Sometimes the error or status messages in webpages would be different from the default error message thrown by Tomcat (or any other server). An important reason for this is websites want to look unique in their approach to their users. So, a customized page for displaying status codes is always better than the standard template. Spring Boot makes i
6 min read
three90RightbarBannerImg