后台转换date格式并用json传回页面

来源:互联网 发布:naca64翼型数据 编辑:程序博客网 时间:2024/05/29 07:06

其实思路有很多,如果是传回给页面的是对象,那用JSTL标签就可以很好的解决问题。

这里我介绍一下传json的时候怎么修改json里的date

一、比较笨但是很好理解的方法:将数据里的date对象遍历出来,进行格式化后存到另一个属性上。返回到页面

@RequestMapping("/showPmRequest")public void showPmRequest(@RequestBody DispatchMessageQueryVo queryVo,HttpServletRequest request,HttpServletResponse response) throws Exception{PageHelper.startPage(queryVo.getPageIndex(), queryVo.getPageSize());List<Map> msgList = distributePeopleService.findMessageList(queryVo);PageInfo<Map> pageInfo = new PageInfo<Map>(msgList);List<Map> list = pageInfo.getList();Contants.convertMapKey2LowerCaseForList(list);int count = (int) pageInfo.getTotal();for (Map map : list) {Date beginDate =  (Date) map.get("begindate");//确定格式SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");//进行格式化if (null!=beginDate) {String date = sFormat.format(beginDate);map.put("begindateString", date);}}        PageModel<Map> pageModel = new PageModel<Map>(list,count);Contants.printJson(pageModel, response);}
以上方法里的sql返回的是一个Map ,所以我使用map.put 即可,如果返回的是一个实体类对象,那么需要在实体类里新增一个例如:begindateString 这样的String对象。然后再通过Gson 传回到页面,在页面我们选择显示begindateString 即可。

二、Gson里提供了相当简单的时间转换方式
public static void printJson(Object object,HttpServletResponse response) throws Exception{Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); String json=gson.toJson(object);response.setCharacterEncoding("UTF-8");PrintWriter out=response.getWriter();out.print(json);System.out.println(json);out.flush();out.close();}

在我原来的GSON工具类里 第一句是 Gson gson = new Gson(); 现在改成Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); 

这样一来,拿到的数据里所有的date 都会被转换,放心大胆的到页面去显示吧!

  

0 0