项目中,经常会用JSONObject插件将JavaBean或List<JavaBean>转换为JSON格式的字符串,而JavaBean的属性有时候会有java.util.Date这个类型的时间对象,这时JSONObject默认会将Date属性转换成这样的格式:
- {"nanos":0,"time":-27076233600000,"minutes":0,"seconds":0,"hours":0,"month":11,"timezoneOffset":-480,"year":-789,"day":5,"date":22}
而这种格式肯定是非常难以理解的,为了将Date转换为我们认识的“yyyy-MM-dd”格式,需要做以下操作。
首先创建一个时间转换器
- publicclassJsonDateValueProcessorimplementsJsonValueProcessor{
- privateStringformat="yyyy-MM-dd";
- publicJsonDateValueProcessor(){
- super();
- }
- publicJsonDateValueProcessor(Stringformat){
- this.format=format;
- @Override
- publicObjectprocessArrayValue(ObjectparamObject,
- JsonConfigparamJsonConfig){
- returnprocess(paramObject);
- publicObjectprocessObjectValue(StringparamString,ObjectparamObject,85); font-weight:bold">privateObjectprocess(Objectvalue){
- if(valueinstanceofDate){
- SimpleDateFormatsdf=newSimpleDateFormat(format,Locale.CHINA);
- returnsdf.format(value);
- returnvalue==null?"":value.toString();
- }