public static String getJsonString4JavaPOJO(Object javaObj,final String dateFomart) {
JSONObject json = null;
try {
/*修复在Integer类型如果为null转换还是null,不会被转为0*/
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerDefaultValueProcessor(Integer.class, new DefaultValueProcessor() {
public Object getDefaultValue(Class type) {
return null;
}
});
jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor(){
@Override
public Object processArrayValue(Object obj, JsonConfig jsonconfig) {
return process(obj);
}
@Override
public Object processObjectValue(String s, Object obj, JsonConfig jsonconfig) {
return process(obj);
}
private Object process(Object obj) {
if (obj == null) {// 如果时间为null,则返回空字串 "yyyy-MM-dd hh:mm:ss"
return "";
}
if (obj instanceof Date) {
obj = new java.util.Date(((Date) obj).getTime());
}
if (obj instanceof java.util.Date) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFomart,
Locale.CHINA);//
return sdf.format(obj);
} else {
return new Object();
}
}
});
/*****end******/
//对象
json = JSONObject.fromObject(javaObj , jsonConfig);
//集合
// json = JSONArray.fromObject(javaObj , jsonConfig);
} catch (Exception e) {
e.printStackTrace();
}
return json.toString();
}
|