Spring Boot REST API - Returning Response in JSON Format
Introduction
In this guide, we will learn how to return a response in JSON format from a Spring Boot REST API. By default, Spring Boot returns responses in JSON, making it the standard format for most RESTful services. JSON is widely used due to its lightweight nature, easy readability, and compatibility with various programming languages.
Why Use JSON in REST APIs?
- Lightweight & Fast: JSON data is compact, making it faster to parse compared to XML.
- Human & Machine Readable: JSON has a simple and structured format that is easy to read and manipulate.
- Widely Supported: JSON is supported across multiple programming languages and frameworks.
- Ideal for Web & Mobile Applications: JSON works well with JavaScript and is natively supported in web and mobile development.
Steps to Implement JSON Response in Spring Boot
1️⃣ Add Required Dependencies
Spring Boot uses Jackson for JSON serialization and deserialization. Jackson is included by default in Spring Boot starters, so no extra dependency is needed. However, ensure that your pom.xml
contains the necessary dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
This ensures that Jackson can automatically convert Java objects to JSON and vice versa.
2️⃣ Create a Model Class (DTO) for JSON Response
We need a model class (DTO) that represents the response data. Jackson automatically serializes objects into JSON.
package com.example.demo.dto;
public class UserResponse {
private String name;
private int age;
private String email;
// Default Constructor
public UserResponse() {}
// Parameterized Constructor
public UserResponse(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
3️⃣ Create a REST Controller
Next, we create a Spring Boot REST Controller that returns the response in JSON format. We use produces = MediaType.APPLICATION_JSON_VALUE
to specify JSON response type.
package com.example.demo.controller;
import com.example.demo.dto.UserResponse;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
public UserResponse getUser() {
return new UserResponse("Ayush", 25, "ayush@example.com");
}
}
4️⃣ Create Main Spring Boot Application Class
The main class is needed to start the Spring Boot application.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
5️⃣ Run the Application and Test the API
Start the Spring Boot application, then send a GET request using Postman, Browser, or Curl:
GET http://localhost:8080/api/user
6️⃣ Expected JSON Response Output
When the API is called, it returns the response in JSON format as shown below:
{
"name": "Ayush",
"age": 25,
"email": "ayush@example.com"
}
Troubleshooting Common Issues
✅ Error: JSON Response Not Showing?
- Ensure that the
jackson-databind
dependency is added. - Check if
produces = MediaType.APPLICATION_JSON_VALUE
is correctly set in the controller. - Use Postman and check the
Accept
header; set it toapplication/json
.
✅ JSON Response Showing as XML?
- If you have
jackson-dataformat-xml
dependency, Spring Boot might return XML. - Remove any
@XmlRootElement
annotations from the model class. - Explicitly request JSON by setting the
Accept
header toapplication/json
.
Summary
✅ Used Jackson for JSON serialization (default in Spring Boot).
✅ Created a DTO class for structured JSON responses.
✅ Developed a REST API that returns JSON using produces = MediaType.APPLICATION_JSON_VALUE
.
✅ Ran and tested the API to verify JSON response output.
Conclusion
Spring Boot provides an easy way to return JSON responses with minimal configuration. With proper setup, JSON-based REST APIs are efficient, fast, and easy to integrate with modern web and mobile applications.
Top comments (0)