Java spring框架 – 如何设置内容类型?

我有一个弹簧动作,我从控制器渲染一些json,在它返回内容类型’text / plain; charset = ISO-8859-1’的那一刻。

如何将其更改为’application / json’?

谢谢乔恩

HttpServletResponse传递给您的操作方法并在其中设置内容类型:

 public String yourAction(HttpServletResponse response) { response.setContentType("application/json"); } 

你尝试过使用MappingJacksonJsonView吗?

Spring-MVC View通过使用Jackson的ObjectMapper序列化当前请求的模型来呈现JSON内容。

它将content-type设置为: application/json

是的,但只有在控制器中抓取HttpServletResponse时才有效。

在Spring 3中,我们被鼓励避免引用servlet域中的任何内容,只保留我们的POJO和注释。 有没有办法在不引用HttpServletResponse的情况下执行此操作? 即,保持自己的纯洁

  @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); } 

如果您需要JSONP (跨站点json请求),您还可以为“回调”部分添加aditional X字节或其他内容。