I have a Spring MVC Controller that returns a JSON String and I would like to set the mimetype to application/json. How can I do that?
@RequestMapping(method=RequestMethod.GET, value="foo/bar")
@ResponseBody
public String fooBar(){
return myService.getJson();
}
The business objects are already available as JSON strings, so using MappingJacksonJsonView
is not the solution for me. @ResponseBody
is perfect, but how can I set the mimetype?
Use ResponseEntity
instead of ResponseBody
. This way you have access to the response headers and you can set the appropiate content type. According to the Spring docs:
The
HttpEntity
is similar to@RequestBody
and@ResponseBody
. Besides getting access to the request and response body,HttpEntity
(and the response-specific subclassResponseEntity
) also allows access to the request and response headers
The code will look like:
@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
String json = "jsonResponse";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}