前言
日常开发中,我们经常使用Gson对实体类进行封装,然后通过接口返回,那么应该会遇到这种情况,当我们使用了LocalDateTime
形式来进行对时间处理的时候,接口返回的不是我们想要的字符串形式,而是下面的这种感觉:
这样的感觉很是不舒服,我们需要对Gson
进行序列化配置
正文
配置方式如下:
package com.zzm.demo.config;
import com.google.gson.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* 优化Gson对LocalDateTime的转换
* @Author i8023tp
**/
@Configuration
public class GsonConfig {
//序列化
final static JsonSerializer<LocalDateTime> jsonSerializerDateTime = (localDateTime, type, jsonSerializationContext)
-> new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
final static JsonSerializer<LocalDate> jsonSerializerDate = (localDate, type, jsonSerializationContext)
-> new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//反序列化
final static JsonDeserializer<LocalDateTime> jsonDeserializerDateTime = (jsonElement, type, jsonDeserializationContext)
-> LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(),
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
final static JsonDeserializer<LocalDate> jsonDeserializerDate = (jsonElement, type, jsonDeserializationContext)
-> LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString(),
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
@Bean
public Gson create() {
return new GsonBuilder()
.setPrettyPrinting()
/* 更改先后顺序没有影响 */
.registerTypeAdapter(LocalDateTime.class, jsonSerializerDateTime)
.registerTypeAdapter(LocalDate.class, jsonSerializerDate)
.registerTypeAdapter(LocalDateTime.class, jsonDeserializerDateTime)
.registerTypeAdapter(LocalDate.class, jsonDeserializerDate)
.create();
}
}
使用Gson
的时候,使用@Autowired
注解引入即可。
重新启动项目,可以看到,返回正常了:
结语
Yo,Peace&Love
Q.E.D.