目录
1 前言
2 方法
2.1 添加@JsonFormat注解
2.2 拓展SpringMVC的消息转化器
2.2.1 编写对象映射器
2.2.2 web层配置类中拓展消息转化器
1 前言
为了符合我们日常的习惯,在对日期类数据进行返回的时候,常常需要对其进行格式化的处理。接下来我将介绍两种常用的方式,来帮我们更快更好的解决此类问题。如下:
2 方法
2.1 添加@JsonFormat注解
我们只需要在实体类的属性上添加@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")即可,如下。其中赋值给pattern的内容为日期的格式,可以自行修改成所需类型。
//其它内容...
public class Test {@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime createTime;@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime updateTime;//其它内容...
}
2.2 拓展SpringMVC的消息转化器
2.2.1 编写对象映射器
固定的模板格式,如下:
//针对LocalDateTime编写的,如果采用其它的如LocalDate等可自行完善添加
public class JacksonObjectMapper extends ObjectMapper {//格式public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";public JacksonObjectMapper() {super();//收到未知属性时不报异常this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);//反序列化时,属性不存在的兼容处理this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);SimpleModule simpleModule = new SimpleModule().addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT))).addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));//注册功能模块 例如,可以添加自定义序列化器和反序列化器this.registerModule(simpleModule);}
}
2.2.2 web层配置类中拓展消息转化器
同样是模板,CV工程师你值得拥有。
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {//其它内容.../*** 扩展SpringMVC的消息转换器* @param converters*/@Overrideprotected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {//创建消息转化器对象MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();//为消息转化器配置一个对象转化器,可以将Java对象序列化为JSON数据converter.setObjectMapper(new JacksonObjectMapper());//将自己的消息转化器加入容器,0代表优先级最高,不会被覆盖converters.add(0,converter);}
}