Spring Boot Web Application Export and Download JSON File
Tags: Spring Boot Download Gson Json
Introduction
In this tutorial we are going to learn how to implement a Spring Boot web application to export JSON and allow users to download as a JSON file via web browser. Via step by step guide we show you how to implement an example web application to export a list of customers to a JSON file.
Create New Spring Boot Web Project
From Spring Tool Suite IDE select menu File > New > Spring Starter Project.
On the New Spring Starter Project popup input new project spring-boot-download-json-file information as following screenshot.
On the New Spring Starter Project Dependencies popup choose dependencies:
- Template Engines: Thymeleaf
- Web: Spring Web
You can also creating new Spring Boot project using Spring initializr online tool at start.spring.io
Add Google Gson Dependency
In this tutorial we use the Gson library to export JSON String from a list of POJO objects so that we need to add this library to our project.
Add the following Gson dependency to your build.gradle file.
compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
Or use the following XML to add dependency in pom.xml file if you are using Maven build for your project.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
For more information about the library you can visit their open source repository at github.com/google/gson
Create Customer Domain Class
Create a new Java package named dev.simplesolution.domain and add Customer class to represent the data we are going to export.
package dev.simplesolution.domain;
public class Customer {
private Integer id;
private String firstName;
private String lastName;
private String email;
private String phone;
public Customer(Integer id, String firstName, String lastName, String email, String phone) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Implement JSON Exporting service
In this step we create a service class and interface to convert Java objects into JSON String.
Create a new Java package named dev.simplesolution.service and add JsonExporter interface.
package dev.simplesolution.service;
import java.util.List;
import dev.simplesolution.domain.Customer;
public interface JsonExporter {
String export(List<Customer> customers);
}
Create a new Java package named dev.simplesolution.service.impl and implement JsonExporterImpl service class.
package dev.simplesolution.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import dev.simplesolution.domain.Customer;
import dev.simplesolution.service.JsonExporter;
@Service
public class JsonExporterImpl implements JsonExporter {
@Override
public String export(List<Customer> customers) {
Gson gson = new Gson();
String customerInJson = gson.toJson(customers);
return customerInJson;
}
}
Implement Download Controller
Create a new Java package named dev.simplesolution.controller and create DownloadController class.
Inject the JsonExporterto the DownloadController and implement a index() method in order to show the index page.
@Controller
public class DownloadController {
@Autowired
private JsonExporter jsonExporter;
@GetMapping("/")
public String index() {
return "index";
}
}
Create a generateCustomerData() method to generate a dummy data list of customers for export later.
private List<Customer> generateCustomerData() {
List<Customer> customers = new ArrayList<Customer>();
Customer customer = new Customer(1, "John", "Doe", "john@simplesolution.dev", "123-456-111");
customers.add(customer);
customer = new Customer(2, "Stella", "Hudson", "stella@simplesolution.dev", "123-456-222");
customers.add(customer);
return customers;
}
Implement download JSON file method.
@GetMapping("/downloadJson")
public ResponseEntity<byte[]> downloadJsonFile() {
List<Customer> customers = generateCustomerData();
String customerJsonString = jsonExporter.export(customers);
byte[] customerJsonBytes = customerJsonString.getBytes();
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=customers.json")
.contentType(MediaType.APPLICATION_JSON)
.contentLength(customerJsonBytes.length)
.body(customerJsonBytes);
}
The final DownloadController class.
package dev.simplesolution.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import dev.simplesolution.domain.Customer;
import dev.simplesolution.service.JsonExporter;
@Controller
public class DownloadController {
@Autowired
private JsonExporter jsonExporter;
@GetMapping("/")
public String index() {
return "index";
}
@GetMapping("/downloadJson")
public ResponseEntity<byte[]> downloadJsonFile() {
List<Customer> customers = generateCustomerData();
String customerJsonString = jsonExporter.export(customers);
byte[] customerJsonBytes = customerJsonString.getBytes();
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=customers.json")
.contentType(MediaType.APPLICATION_JSON)
.contentLength(customerJsonBytes.length)
.body(customerJsonBytes);
}
private List<Customer> generateCustomerData() {
List<Customer> customers = new ArrayList<Customer>();
Customer customer = new Customer(1, "John", "Doe", "john@simplesolution.dev", "123-456-111");
customers.add(customer);
customer = new Customer(2, "Stella", "Hudson", "stella@simplesolution.dev", "123-456-222");
customers.add(customer);
return customers;
}
}
Create HTML View to show Download page
Create a new HTML view file at \src\main\resources\templates\index.html to show the download button.
In this HTML we also use Bootstrap CSS library.
<!DOCTYPE html>
<html>
<head>
<title>Download JSON File</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
</head>
<body class="container">
<br>
<p>Click the button below to download JSON file.</p>
<a href="/downloadJson" class="btn btn-primary">
Download JSON File
</a>
</body>
</html>
Final Application
The final Spring Boot web application structure looks like the following screenshot.
Run the Spring Boot web application and visit http://localhost:8080/ on your browser to open the web user interface as following screenshot.
Then try to click on the Download JSON File button to download the file in JSON format.
Conclusion
With the step by step guide above we have learned how to create a Spring Boot web application and implement a feature to allow users download data in a JSON file format. We also learn how to use Google Gson library to convert a list of Java objects into a JSON String.
Download Source Code
The source code in this article can be found at: github.com/simplesolutiondev/spring-boot-download-json-file
or clone at:
git clone https://github.com/simplesolutiondev/spring-boot-download-json-file.git
or download at:
Happy Coding 😊