Question
How can I return a JSON object from my Spring Boot RestController without encountering exceptions?
@RestController
@RequestMapping("/api")
class MyRestController {
@GetMapping(path = "/hello")
public ResponseEntity<Map<String, String>> sayHello() {
Map<String, String> response = new HashMap<>();
response.put("aa", "bb");
return ResponseEntity.ok(response);
}
}
Answer
When trying to return a JSON object using `org.json.JSONObject` in a Spring Boot application, you may encounter an exception due to missing message converters capable of handling that type. This guide will detail the correct approach to return JSON responses and solve the common issue of 'no converter found'.
import org.springframework.http.ResponseEntity;
@RestController
@RequestMapping("/api")
class MyRestController {
@GetMapping(path = "/hello")
public ResponseEntity<Map<String, String>> sayHello() {
Map<String, String> response = new HashMap<>();
response.put("aa", "bb");
return ResponseEntity.ok(response);
}
}
Causes
- The `org.json.JSONObject` type is not supported by default in Spring Boot because there is no appropriate HttpMessageConverter registered for it.
- Spring Boot uses Jackson for JSON binding which works with POJOs (Plain Old Java Objects) or collections (Lists, Maps) instead.
Solutions
- Use a standard Java type like a Map or a custom class to represent your JSON structure.
- Ensure the ResponseEntity class is used along with appropriate HTTP status codes.
Common Mistakes
Mistake: Returning an object type that isn't recognized by Spring's HttpMessageConverters.
Solution: Instead of returning org.json.JSONObject, return a standard Java type such as Map or a custom POJO.
Mistake: Not using ResponseEntity for structured HTTP responses.
Solution: Wrap your response in ResponseEntity to control the status and response headers.
Helpers
- Spring Boot return JSON
- Spring Boot RestController
- org.json.JSONObject
- ResponseEntity Spring Boot
- JSON response in Spring Boot