java 解决controller层日期返回long型
java 解决controller层日期返回long型
在一个项目中都会存在拦截器,我们创建拦截器 MyWebAppConfigurer extends WebMvcConfigurationSupport在自定义的拦截器中 MyWebAppConfigurer 加入方法,如下
@Override
public void configureMessageConverters(List
<HttpMessageConverter
<?>> converters
) {
super.configureMessageConverters(converters
);
FastJsonHttpMessageConverter converter
= new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig
= new FastJsonConfig();
fastJsonConfig
.setSerializerFeatures(
SerializerFeature
.DisableCircularReferenceDetect
,
SerializerFeature
.PrettyFormat
,
SerializerFeature
.WriteMapNullValue
);
fastJsonConfig
.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig
.setSerializeConfig(getSerializeConfig());
converter
.setFastJsonConfig(fastJsonConfig
);
List
<MediaType> mediaTypeList
= new ArrayList<>();
mediaTypeList
.add(MediaType
.APPLICATION_JSON
);
mediaTypeList
.add(MediaType
.APPLICATION_FORM_URLENCODED
);
converter
.setSupportedMediaTypes(mediaTypeList
);
converters
.add(converter
);
}
public SerializeConfig
getSerializeConfig() {
SerializeConfig config
= new SerializeConfig();
config
.put(BigDecimal
.class, new BigDecimalFormatSerializer());
return config
;
}
其中存在一个Bigdecimal格式化, 如下:
public class BigDecimalFormatSerializer implements ObjectSerializer {
@Override
public void write(JSONSerializer jsonSerializer
, Object object
, Object fieldName
, Type fieldType
, int features
) throws IOException
{
SerializeWriter out
= jsonSerializer
.getWriter();
if(object
== null
){
out
.writeString("0.00");
}else{
BigDecimal bigDecimal
= (BigDecimal
)object
;
String value
= bigDecimal
.toString();
out
.writeString(value
);
}
}
}
添加如下方法之后在controller层就会返回 格式化的日期,不再是long型了。。。。。