Spring MVC 4: "application/json" Content Type is not being set correctly
First thing to understand is that the RequestMapping#produces()
element in
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
serves only to restrict the mapping for your request handlers. It does nothing else.
Then, given that your method has a return type of String
and is annotated with @ResponseBody
, the return value will be handled by StringHttpMessageConverter
which sets the Content-type
header to text/plain
. If you want to return a JSON string yourself and set the header to application/json
, use a return type of ResponseEntity
(get rid of @ResponseBody
) and add appropriate headers to it.
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")public ResponseEntity<String> bar() { final HttpHeaders httpHeaders= new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);}
Note that you should probably have
<mvc:annotation-driven />
in your servlet context configuration to set up your MVC configuration with the most suitable defaults.
As other people have commented, because the return type of your method is String
Spring won't feel need to do anything with the result.
If you change your signature so that the return type is something that needs marshalling, that should help:
@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")@ResponseBodypublic Map<String, Object> bar() { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("test", "jsonRestExample"); return map;}
Use jackson library and @ResponseBody
annotation on return type for the Controller.
This works if you wish to return POJOs represented as JSon. If you woud like to return String and not POJOs as JSon please refer to Sotirious answer.