java date型別轉換為json
阿新 • • 發佈:2019-02-01
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
/**
* @author zhang yanan
* @createTime 2011-3-12 下午02:57:17
* @desc Json處理java物件到json格式轉換的日期處理類
*
*/
public class JsonDateValueProcessor implements JsonValueProcessor {
private String datePattern = "yyyy-MM-dd HH:mm:ss";// 日期格式
public JsonDateValueProcessor() {
super();
}
// 建構函式
public JsonDateValueProcessor(String format) {
super();
this.datePattern = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
// TODO Auto-generated method stub
return process(value);
}
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
// TODO Auto-generated method stub
return process(value);
}
private Object process(Object value) {
try {
if (value instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(datePattern,
Locale.UK);
return sdf.format((Date) value);
}
return value == null ? "" : value.toString();
} catch (Exception e) {
return "";
}
}
public String getDatePattern() {
return datePattern;
}
public void setDatePattern(String datePaterns) {
this.datePattern = datePaterns;
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
Users user = new Users();
user.setDate(new Date());
list.add(user);
JsonConfig jsonConfig = new JsonConfig();
// 設定javabean中日期轉換時的格式
jsonConfig.registerJsonValueProcessor(Date.class,
new JsonDateValueProcessor("yyyy-MM-dd HH:mm:ss"));
// 獲取json陣列
JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
System.out.println(jsonArray.toString());
}
}