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.
Here's an example of how you can do this in a Spring Boot controller:
@GetMapping("/api/object")
@ResponseBody
public 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 want to have more control over the formatting of the JSON response, you can use the ObjectMapper
class to serialize the object to a JSON string:
@GetMapping("/api/object")
@ResponseBody
public String getObject() throws JsonProcessingException {
Map<String, Object> object = new HashMap<>();
object.put("key1", "value1");
object.put("key2", "value2");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
This will return the same JSON object as before, but with the formatting specified by the ObjectMapper
configuration.
I hope this helps! Let me know if you have any questions.