json-lib中在讲一个date类型转化时,将会有一个问题:json对象中该date类型将按照Java中类字段的形式保存下来,在程序中使用时及其不方便,现将解决方法贴出,如下所示:
1 首先重写一个Processor
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 HH:mm:ss";
private DateFormat dateFormat;
/**
* 构造方法.
*
* @param datePattern 日期格式
*/
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) {
return dateFormat.format((Date) value);
}
}
2 将上面的processor配置到使用的jsonConfig中
/**
* 配置json-lib需要的excludes和datePattern.
*
* @param excludes 不需要转换的属性数组,如果没有可以设置为null
* @param datePattern 日期转换模式
* @return JsonConfig 根据excludes和dataPattern生成的jsonConfig,用于write
*/
public static JsonConfig configJson(String[] excludes, String datePattern) {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(excludes);
jsonConfig.setIgnoreDefaultExcludes(false);
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(datePattern));
return jsonConfig;
}
3将Object或者Array转化为JSON
jsonArray = JSONArray.fromObject(someArray, config);
jsonObject=JSONObject.fromObject(object, jsonConfig);
另外还有另外一个办法,即在页面进行转化,可使用以下一句代码搞定:
formatDate(new Date(commentDate["time"]),"yyyy-MM-dd HH:mm:ss")
不过必须使用本文附件的js