不使用@ResponseBody注解返回json数据给前台

项目中用Spring的时候,大都是后端返回json数据给前端,现在我有个需求是要把对象装换位json的同时,json的key要转换为中文的,看了资料,发现Spring使用的@ResponseBody可以通过jackson的@JsonProperty 注解,把属性名称序列化为另外一个名称(SpringMVC默认使用的是jackson),比如

@JsonProperty("总数") public int total; 

这样输出json的时候就是{“总数”:100} 了 ,而不是 {“total”:100}

用这个不知道什么原因,对List里的对象数据没起作用,换了种思路

首先想到了不用@ResponseBody,自己转换json, 这样就可以用Gson或者fastJson这一类的json工具了,我用的是Gson

@RequestMapping(value="/list", method=RequestMethod.GET)
//@ResponseBody
public void productlist(@ModelAttribute @Valid Param param,HttpServletResponse response)
 throws IOException {
    int total = service.getProductTotalById(param.id);
    ProductListResult result = new ProductListCnResult(ErrorCode.SUCCESS, total);
      if(total > 0){
         result.list = productService.findProductByFeedId(param.feed_id);
      }
      //让浏览器用utf8来解析返回的数据
      response.setHeader("Content-type", "text/html;charset=UTF-8");
      //告诉servlet用UTF-8转码,而不是用默认的ISO8859
      response.setCharacterEncoding("UTF-8");
      //不需要返回值
      response.getWriter().write(result.toString());
   }
}

返回对象的实体类用@SerializedName("xxx") 转换即可
发布了69 篇原创文章 · 获赞 123 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/u011870547/article/details/82419925