10

I have a spring action that I am rendering some json from the controller, at the minute its returning the content type 'text/plain;charset=ISO-8859-1'.

How can I change this to be 'application/json'?

slartidan
  • 20,403
  • 15
  • 83
  • 131
Ian morgan
  • 935
  • 3
  • 11
  • 15

4 Answers4

19

Pass the HttpServletResponse to your action method and set the content type there:

public String yourAction(HttpServletResponse response) {
    response.setContentType("application/json");
}
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
5

Did you try using the MappingJacksonJsonView?

Spring-MVC View that renders JSON content by serializing the model for the current request using Jackson's ObjectMapper.

It sets the content-type to: application/json.

reevesy
  • 3,452
  • 1
  • 26
  • 23
Thomas Vanstals
  • 174
  • 1
  • 2
  • Heh, I was doing manually what has already been provided for me by Spring. Thanks for the pointer :) – tmbrggmn Jul 17 '10 at 18:39
3
 @RequestMapping(value = "jsonDemoDude", method = RequestMethod.GET)
    public void getCssForElasticSearchConfiguration(HttpServletResponse response) throws IOException {        
        String jsonContent= ...;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response);
        wrapper.setContentType("application/json;charset=UTF-8");
        wrapper.setHeader("Content-length", "" + jsonContent.getBytes().length);
        response.getWriter().print(jsonContent);
}

You can also add the aditional X bytes or whatever for "callback" part in case you want JSONP ( cross site json request ) .

reevesy
  • 3,452
  • 1
  • 26
  • 23
jNayden
  • 1,592
  • 2
  • 17
  • 29
2

Yes, but this only works if one is grabbing the HttpServletResponse in the controller.

In Spring 3 we're being encouraged to avoid references to anything in the servlet domain, keeping things solely to our POJOs and annotations. Is there a way to do this without referencing the HttpServletResponse? I.e., keeping ourselves pure?

Ichiro Furusato
  • 620
  • 6
  • 12
  • 1
    You could use a JSR-311 (JAX-RS) implementation, that provides explicit control of content types via annotations. Here is a discussion of those: http://stackoverflow.com/questions/1710199/which-is-the-best-java-rest-api-restlet-or-jersey – FelixM Jan 28 '11 at 15:10
  • 1
    Yes, you can use the "produces" attribute of the @RequestMapping annotation, see http://stackoverflow.com/a/12023805/10433 for an example of setting the encoding this way. – Andrew Swan Feb 28 '13 at 23:55