用springmvc作接口时返回json数据中文乱码

来源:互联网 发布:网络拓扑图图标 编辑:程序博客网 时间:2024/05/16 04:34

           以前都是用springmvc做web项目,浏览器访问,所以没出现过fastjson中文乱码的问题,今天要做一个接口,结果杯具了中文乱码。

          接口调用拿到返回数据疯狂的修改编码,结果无效,考虑是不是json封装时就出现了乱码了。结果一看,果然是得。后来找到如下方法得以解决:

@RequestMapping(value="/getWork.html" ,method=RequestMethod.POST)
public ResponseEntity<String>  getWork(@Valid ViewYyRecord record,HttpServletResponse response) throws UnsupportedEncodingException {
JSONObject ret=workService.getWork(record);
System.out.println(ret.toString());
HttpHeaders headers = new HttpHeaders();   
        MediaType mediaType=new MediaType("text","html",Charset.forName("GBK"));   
        headers.setContentType(mediaType);   
        ResponseEntity<String> responseEntity =new ResponseEntity<String>(ret.toString(),headers,HttpStatus.OK);   
        return responseEntity;  
}

返回的是ResponseEntity<String>其实还是json字符串,很方便。赞!

0 0
原创粉丝点击