jackson提供对LocalDate的支持
SpringBoot默认使用jackson来进行json格式转换,我们在配置文件中加入如下配置可以统一的改变Spring MVC返回值的日期格式类型
spring.jackson.date-format=yyyy-MM-dd
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-dates-as-timestamps=false
但是这个配置对于java8新提供的日期APILocalDate、LocalDateTime等无效。
解决办法
引入依赖
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.8.9</version>
</dependency>
启动主类添加如下代码
@SpringBootApplication
public class GroupApplication {
public static void main(String[] args) {
SpringApplication.run(GroupApplication.class, args);
}
@Bean(name = "mapperObject")
public ObjectMapper getObjectMapper() {
ObjectMapper om = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
om.registerModule(javaTimeModule);
return om;
}
}
使用Jackson格式化LocalDate对象
LocalDate可以很方便的对日期进行处理,但是在返回给前端时,展示为如下的JSON结构:
{
"dayOfWeek": "FRIDAY",
"month": "JANUARY",
"year": 2020,
"dayOfMonth": 3,
"era": "CE",
"dayOfYear": 3,
"monthValue": 1,
"chronology": {
"calendarType": "iso8601",
"id": "ISO"
}
}
前端组件就很难处理了。接下来,我们需要将此属性反序列化并从JSON字符串序列化。为此,我们可以使用@JsonDeserialize和@JsonSerialize来注释该类的LocalDate属性,时期成为前端组件需要的String格式。
实现LocalDateDeserializer和LocalDateSerializer
下面是LocalDateSerializerand LocalDateDeserializer类的定义。
public class LocalDateDeserializer extends StdDeserializer<LocalDate> {
protected LocalDateDeserializer() {
super(LocalDate.class);
}
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
return LocalDate.parse(parser.readValueAs(String.class));
}
}
public class LocalDateSerializer extends StdSerializer<LocalDate> {
public LocalDateSerializer() {
super(LocalDate.class);
}
@Override
public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException {
generator.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}
实体类添加注解
实体类添加如下的注解
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate date;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。