准备工作:
json-2.4.jar
ezmorph-1.0.6.jar
类
public class JsonDateValueProcessor implements JsonValueProcessor {
private String datePattern = "yyyy-MM-dd";
public JsonDateValueProcessor() {
super();
}
public JsonDateValueProcessor(String format) {
super();
this.datePattern = format;
}
@Override
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value);
}
@Override
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
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 pDatePattern) {
datePattern = pDatePattern;
}
}
1.json转bean
String[] dateFmts = new String[] { "yyyy/MM/dd", "yyyy-MM-dd HH:mm:ss" };
(没有时分秒去HH:mm:ss掉即可)
JSONUtils.getMorpherRegistry().registerMorpher( new DateMorpher(dateFmts));
ReportRfid rr = (ReportRfid)JSONObject.toBean(JSONObject,ReportRfid.class);
2.bean转json
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class , new JsonDateValueProcessor());
JSONArray tempJsonArray = JSONArray.fromObject(tempList,jsonConfig);
单个bean同上