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:

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:

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:

That’s all about returning a JSON object as response in Spring Boot.