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?
The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
As seen in earlier section, the web container directs all MVC request to the Spring DispatcherServlet. The Spring Front controller will intercept the request and will find the appropriate handler based on the handler mapping (configured in Spring configuration files or annotation).
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); }
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:
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET value = "/foo/bar") @ResponseBody public Bar fooBar(){ return myService.getBar(); }
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With