Extjs4 Grid显示util.Date时间问题

从数据库取得的date类型为java.sql.date,如果直接放入list中,然后在转json数据的时候会出现异常,

net.sf.json.JSONException: java.lang.reflect.InvocationTargetException

一种解决办法是在放入list之前,直接转为java.util.date,但是这样在前台取不到值,因为格式不对,下面介绍我的之中方法:

java代码:

JsonConfig cfg = new JsonConfig();    
cfg.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor());    
  
  
JSONArray jsonArray = JSONArray.fromObject(users,cfg);

DateJsonValueProcessor.java:

package servlet;  
  
import java.sql.Timestamp;  
import java.text.DateFormat;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import net.sf.json.JsonConfig;  
import net.sf.json.processors.JsonValueProcessor;  
  
public class DateJsonValueProcessor implements JsonValueProcessor {  
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";  
    private DateFormat dateFormat;  
  
    public DateJsonValueProcessor() {  
        this(DEFAULT_DATE_PATTERN);  
    }  
  
    public DateJsonValueProcessor(String datePattern) {  
        try {  
            dateFormat = new SimpleDateFormat(datePattern);  
        } catch (Exception ex) {  
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);  
        }  
    }  
  
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {  
        return process(value);  
    }  
  
    public Object processObjectValue(String key, Object value,  
            JsonConfig jsonConfig) {  
        return process(value);  
    }  
  
    private Object process(Object value) {  
        if (value instanceof Timestamp)  
            return dateFormat.format((Timestamp) value);  
        else if (value instanceof Date)  
            return dateFormat.format((Date) value);  
        else if (value == null)  
            return "";  
        else  
            return value.toString();  
    }  
}

 

发表评论