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?
Register
org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
as the message converter and return the object directly from the method.and the controller:
This requires the dependency
org.springframework:spring-webmvc
.I don't think this is possible. There appears to be an open Jira for it:
SPR-6702: Explicitly set response Content-Type in @ResponseBody
I don't think you can, apart from
response.setContentType(..)
Use
ResponseEntity
instead ofResponseBody
. This way you have access to the response headers and you can set the appropiate content type. According to the Spring docs:The code will look like:
I would consider to refactor the service to return your domain object rather than JSON strings and let Spring handle the serialization (via the
MappingJacksonHttpMessageConverter
as you write). As of Spring 3.1, the implementation looks quite neat:Comments:
First, the
<mvc:annotation-driven />
or the@EnableWebMvc
must be added to your application config.Next, the produces attribute of the
@RequestMapping
annotation is used to specify the content type of the response. Consequently, it should be set to MediaType.APPLICATION_JSON_VALUE (or"application/json"
).Lastly, Jackson must be added so that any serialization and de-serialization between Java and JSON will be handled automatically by Spring (the Jackson dependency is detected by Spring and the
MappingJacksonHttpMessageConverter
will be under the hood).You may not be able to do it with @ResponseBody, but something like this should work: