@ResponseBody 解决日期返回long型

tech2022-10-15  126

java 解决controller层日期返回long型

java 解决controller层日期返回long型

在一个项目中都会存在拦截器,我们创建拦截器 MyWebAppConfigurer extends WebMvcConfigurationSupport在自定义的拦截器中 MyWebAppConfigurer 加入方法,如下 /** * 解决日期返回long型 * @param converters */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters);//json序列化的配置 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); // fastJsonConfig.setSerializerFeatures( // SerializerFeature.PrettyFormat, // SerializerFeature.WriteMapNullValue, // SerializerFeature.WriteNullListAsEmpty, // SerializerFeature.WriteNullStringAsEmpty, // SerializerFeature.IgnoreNonFieldGetter // ); fastJsonConfig.setSerializerFeatures( SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.PrettyFormat, // SerializerFeature.IgnoreNonFieldGetter 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型了。。。。。

最新回复(0)