在将java.util.Date 类型字段转为json时,获取时取到的为[object object],解决方法为:在讲对象转化为json格式是添加自定义的日期格式转化类,具体代码如下:
public class DateJsonValueProcessor implements JsonValueProcessor { private String format = "yyyy-MM-dd"; public DateJsonValueProcessor() { } public DateJsonValueProcessor(String format) { this.format = format; } public Object processArrayValue(Object value, JsonConfig jsonConfig) { String[] obj = {}; if(value!=null) { if (value instanceof Date[]) { SimpleDateFormat sf = new SimpleDateFormat(format); Date[] dates = (Date[]) value; obj = new String[dates.length]; for (int i = 0; i < dates.length; i++) { obj[i] = sf.format(dates[i]); } } } return obj; } public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { if(value!=null) { if (value instanceof Date) { String str = new SimpleDateFormat(format).format((Date) value); return str; } } return value; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } }
使用方法:
JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
将json返回客户端
HttpServletResponse response = this.getHttpResponse(); response.setContentType("text/plain;charset=UTF-8"); response.setHeader("Cache-Control","no-cache"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); try { response.getWriter().print(JSONObject.fromObject(conObj,jsonConfig)); } catch (Exception e) { e.printStackTrace(); } return null;