项目中,经常会用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}@H_502_12@
而这种格式肯定是非常难以理解的,为了将Date转换为我们认识的“yyyy-MM-dd”格式,需要做以下操作。
首先创建一个时间转换器
- public@H_502_12@class@H_502_12@JsonDateValueProcessorimplements@H_502_12@JsonValueProcessor{@H_502_12@
- private@H_502_12@Stringformat="yyyy-MM-dd"@H_502_12@;@H_502_12@
- @H_502_12@
- public@H_502_12@JsonDateValueProcessor(){@H_502_12@
- super@H_502_12@();@H_502_12@
- }@H_502_12@
- public@H_502_12@JsonDateValueProcessor(Stringformat){@H_502_12@
- this@H_502_12@.format=format;@H_502_12@
- @Override@H_502_12@@H_502_12@
- public@H_502_12@ObjectprocessArrayValue(ObjectparamObject,@H_502_12@
- JsonConfigparamJsonConfig){@H_502_12@
- return@H_502_12@process(paramObject);@H_502_12@
- public@H_502_12@ObjectprocessObjectValue(StringparamString,ObjectparamObject,85); font-weight:bold">private@H_502_12@Objectprocess(Objectvalue){@H_502_12@
- if@H_502_12@(valueinstanceof@H_502_12@Date){@H_502_12@
- SimpleDateFormatsdf=new@H_502_12@SimpleDateFormat(format,Locale.CHINA);@H_502_12@
- return@H_502_12@sdf.format(value);@H_502_12@
- return@H_502_12@value==null@H_502_12@?""@H_502_12@:value.toString();@H_502_12@
- }@H_502_12@