Skip to content

Instantly share code, notes, and snippets.

@monjer
Last active December 26, 2015 17:59
Show Gist options
  • Select an option

  • Save monjer/7191054 to your computer and use it in GitHub Desktop.

Select an option

Save monjer/7191054 to your computer and use it in GitHub Desktop.
json-lib 日期时间配置
package com.java.helper;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsDateJsonValueProcessor;
import net.sf.json.processors.JsonValueProcessor;
/**
* @author manjun.han
* @date 2013.10.10
* @purpose json-lib的帮助类,参见:http://json-lib.sourceforge.net/
*
*/
public class JsonlibHelper {
/**
* 使用自定义日期格式,处理Date对象
* @param javaObj,包含Date类型实例的java对象
* @return JSON
*/
public static final JSON serializerObjWithFormatDate(Object javaObj){
JsonConfig jsonCfg = JsonlibHelper.getDefaultJsonCfgWithFormatDate();
return JSONSerializer.toJSON(javaObj ,jsonCfg);
}
/**
* 以dateFormatPattern格式,创建新的JsonConfig对象
* @param dateFormatPattern Date的格式化模式
* @return
*/
public static JsonConfig getJsonCfgWithFormatDate(String dateFormatPattern){
final SimpleDateFormat fm = new SimpleDateFormat(dateFormatPattern);
JsonConfig jsonCfg = new JsonConfig();
jsonCfg.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
@Override
public Object processObjectValue(String key, Object value, JsonConfig cfg) {
if (value == null) {
return "";
} else {
return fm.format((Date)value);
}
}
@Override
public Object processArrayValue(Object date, JsonConfig arg1) {
return fm.format((Date)date);
}
});
return jsonCfg ;
}
/**
* 以yyyy-MM-dd HH:mm:ss格式创建JsonConfig对象
* @return
*/
public static JsonConfig getDefaultJsonCfgWithFormatDate(){
String pattern = "yyyy-MM-dd HH:mm:ss";
return JsonlibHelper.getJsonCfgWithFormatDate(pattern);
}
/**
* 使用符合Javascript中Date类型的数据格式转换java对象中的java.util.Date实例
* 转换后的Date类型的对象所产生的json数据如:
* {
* dateFile:{
* "year":2013,
* "month":9,
* "day":9,
* "hours":21,
* "minutes":22,
* "seconds":41,
* "milliseconds":991
* }
* }
* @param javaObj
* @return JSON
*/
public static final JSON serializerObjWithJSDate(Object javaObj){
JsonConfig jsonCfg = new JsonConfig();
jsonCfg.registerJsonValueProcessor(Date.class,new JsDateJsonValueProcessor());
return JSONSerializer.toJSON(javaObj, jsonCfg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment