JSON通过配置文件格式化时间属性(解决[object Object]问题)
2015-09-02 11:20
686 查看
前段时间项目实战,遇到一个问题,后台通过JSON转变数据交换格式,然后在前台输出结果时,对象中的时间显示竟然是[object Object],思考很久,查阅网上资料,才找到解决办法:
关键代码是:
JSON时间处理的工具类代码如下:
这样一来,JSON格式的时间就可以在前台页面进行格式化输出了
try { HttpSession session = request.getSession(); Employee employee = (Employee)session.getAttribute("employee"); int empId = employee.getEmpId(); response.setContentType("text/html;charset=UTF-8"); JsonConfig config = new JsonConfig(); config.setIgnoreDefaultExcludes(false); config.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor("yyyy-MM-dd")); List<LeaveApplication> leaveApplicationList = leaveApplicationService.findByEmpId(empId); JSONArray resultArray = JSONArray.fromObject(leaveApplicationList,config); String lList = "{\"total\":"+leaveApplicationService.personalTotalSize(empId)+",\"rows\":"+resultArray+"}"; PrintWriter out = response.getWriter(); out.write(lList); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); }
关键代码是:
JsonConfig config = new JsonConfig(); config.setIgnoreDefaultExcludes(false); config.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor("yyyy-MM-dd")); List<LeaveApplication> leaveApplicationList = leaveApplicationService.findByEmpId(empId); JSONArray resultArray = JSONArray.fromObject(leaveApplicationList,config); String lList = "{\"total\":"+leaveApplicationService.personalTotalSize(empId)+",\"rows\":"+resultArray+"}";
JSON时间处理的工具类代码如下:
package com.ghost.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; public class JsonDateValueProcessor implements JsonValueProcessor { private String format ="yyyy-MM-dd"; public JsonDateValueProcessor() { super(); } public JsonDateValueProcessor(String format) { super(); this.format = format; } @Override public Object processArrayValue(Object paramObject, JsonConfig paramJsonConfig) { return process(paramObject); } @Override public Object processObjectValue(String paramString, Object paramObject, JsonConfig paramJsonConfig) { return process(paramObject); } private Object process(Object value){ if(value instanceof Date){ SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.CHINA); return sdf.format(value); } return value == null ? "" : value.toString(); } }
这样一来,JSON格式的时间就可以在前台页面进行格式化输出了
相关文章推荐
- Html emed 和 object
- c语言, objective code(new 2)
- ObjectAid 类图生产工具使用
- JSONObject 的使用学习
- objective-c基础教程——学习小结
- swfobject.js视频播放插件
- JsonObject
- 对象类型object
- gameobject与Gameobject
- Minimize Importing Header 学习
- Familiarize Yourself with ObjC's Roots学习
- Objective-C 程序设计(第四版)复习摘要(上)
- [objective_[getter器和setter器的使用]
- Objective-c 之数组NSArray 可变数组NSMutableArray
- Objective-C 【autorelease基本使用】
- Objective-C 【autorelease基本使用】
- Objective-C之Mark
- springmvc中 ajax请求错误,返回406,并一直进入error的回调方法,以及返回参数为Object
- json to object
- NSObject.h解(一)