寫一個DateJsonValueProcessor.java
package anni.core.web.json;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
/**
* @author Lingo
* @since 2007-08-02
*/
public class DateJsonValueProcessor implements JsonValueProcessor {
public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
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);
}
}
然後在bean -> json的時候
/**
* write.
*
* @param bean obj
* @param writer 輸出流
* @param excludes 不轉換的屬性數組
* @param datePattern date到string轉換的模式
* @throws Exception 寫入數據可能出現異常
*/
public static void write(Object bean, Writer writer,
String[] excludes, String datePattern) throws Exception {
JsonConfig jsonConfig = configJson(excludes, datePattern);
JSON json = JSONSerializer.toJSON(bean, jsonConfig);
json.write(writer);
}
/**
* 配置json-lib需要的excludes和datePattern.
*
* @param excludes 不需要轉換的屬性數組
* @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;
}