W3docs

Returning JSON object as response in Spring Boot

To return a JSON object as a response in Spring Boot, you can use the @ResponseBody annotation and the ObjectMapper class.

To return a JSON object as a response in Spring Boot, you can rely on Spring's automatic JSON conversion by returning a Java object directly, or use the ObjectMapper class for manual serialization.

Here's an example using @RestController, which is the modern standard for Spring Boot APIs:


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
public class JsonController {
    @GetMapping("/api/object")
    public Map<String, Object> getObject() {
        Map<String, Object> object = new HashMap<>();
        object.put("key1", "value1");
        object.put("key2", "value2");
        return object;
    }
}

This controller method will return a JSON object that looks like this:


{
  "key1": "value1",
  "key2": "value2"
}

If you need more control over the serialization process, you can use the ObjectMapper class to manually convert the object to a JSON string:


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
public class JsonController {
    @GetMapping("/api/object-manual")
    public String getObjectManual() throws JsonProcessingException {
        Map<String, Object> object = new HashMap<>();
        object.put("key1", "value1");
        object.put("key2", "value2");

        ObjectMapper mapper = new ObjectMapper();
        // new ObjectMapper() outputs compact JSON by default
        return mapper.writeValueAsString(object);
    }
}

This will return the same JSON object as before. Note that new ObjectMapper() outputs compact JSON by default; pretty printing requires explicit configuration (e.g., mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object)).

I hope this helps! Let me know if you have any questions.