Return JSON response in Spring Boot
This post will discuss how to return JSON object as response in Spring Boot.
There are several ways to return JSON object as response in Spring Boot, depending on the scenario and the level of control we want. Here are some of the possible solutions:
1. Using @ResponseBody Annotation
We can use the @ResponseBody annotation on our controller methods and return a JSON object, a POJO, a map, or a string that represents the JSON data. Spring Boot will use Jackson to convert the return value to JSON and send it to the client. For example, we can use the org.json.JSONObject class to create and return a JSON object as follows:
|
1 2 3 4 5 6 7 8 |
@GetMapping(path = "/hello") @ResponseBody public JSONObject sayHello() { JSONObject jsonObject = new JSONObject(); jsonObject.put("status", true); jsonObject.put("message", "Success"); return jsonObject; } |
2. Using ResponseEntity Class
Another option is to use the ResponseEntity class to wrap our response data and specify the HTTP status code with headers. This gives us more flexibility and control over the response. For example, we can use the ResponseEntity.ok() method to create a response entity with a 200 (OK) status code and a JSON object as the body as follows:
|
1 2 3 4 5 6 7 |
@GetMapping(path = "/hello") public ResponseEntity<JSONObject> sayHello() { JSONObject jsonObject = new JSONObject(); jsonObject.put("status", true); jsonObject.put("message", "Success"); return ResponseEntity.ok(jsonObject); } |
3. Using Custom Class
We can create a custom response class that contains the fields that we want to send as JSON data. For example, we can create a class named UserResponse that has fields for status and message. Then we can return an instance of this class from our controller method and Spring Boot will automatically serialize it to JSON. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class UserResponse { private boolean status; private String message; public UserResponse(boolean status, String message) { this.status = status; this.message = message; } // getters, and setters } @GetMapping(path = "/users") public UserResponse getAllUsers() { List<User> users = repository.findAll(); // get all users from db UserResponse userResponse = new UserResponse(true, "Success"); return userResponse; } |
That’s all about returning a JSON object as response in Spring Boot.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)