springboot?接收LocalDateTime方式
本文基于jdk8。
1.標準日期格式轉換
本類型是指前端傳遞類似"yyyy-MM-dd HH:mm:ss"格式字符串,后端以 LocalDateTime類型接收。
spring默認的使用jackson,故添加maven依賴,可參考官方文檔:
<dependency> ? ? <groupId>com.fasterxml.jackson.module</groupId> ? ? <artifactId>jackson-module-parameter-names</artifactId> </dependency> <dependency> ? ? <groupId>com.fasterxml.jackson.datatype</groupId> ? ? <artifactId>jackson-datatype-jdk8</artifactId> </dependency> <dependency> ? ? <groupId>com.fasterxml.jackson.datatype</groupId> ? ? <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
添加一個配置類
@Configuration
public class DateConfiguration {
?? ?@Bean
?? ?public ObjectMapper objectMapper(){
?? ??? ?return new ObjectMapper()
?? ??? ??? ??? ?.registerModule(new ParameterNamesModule())
?? ??? ??? ??? ?.registerModule(new Jdk8Module())
?? ??? ??? ??? ?.registerModule(new JavaTimeModule());
?? ?}
}基礎配置完成,使用時在對應字段添加@DateTimeFormat 進行反序列化或者@JsonFormat序列化。
2.非json請求時間戳轉換
本類型指在前端非json請求,傳遞參數為時間戳,然后轉為LocalDateTime。
可在上文基礎上添加配置,示例如下:
@Configuration
public class DateConfiguration {
?? ?@Bean
?? ?public ObjectMapper objectMapper(){
?? ??? ?return new ObjectMapper()
?? ??? ??? ??? ?.registerModule(new ParameterNamesModule())
?? ??? ??? ??? ?.registerModule(new Jdk8Module())
?? ??? ??? ??? ?.registerModule(new JavaTimeModule());
?? ?}
? ? @Bean
? ? public Formatter<LocalDateTime> localDateTimeFormatter() {
? ? ? ? return new Formatter<LocalDateTime>() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public LocalDateTime parse(String text, Locale locale) ?{
? ? ? ? ? ? ? ? return Instant
? ? ? ? ? ? ? ? ? ? ? ? .ofEpochMilli(Long.parseLong(text))
? ? ? ? ? ? ? ? ? ? ? ? .atZone(ZoneOffset.ofHours(8))
? ? ? ? ? ? ? ? ? ? ? ? .toLocalDateTime();
? ? ? ? ? ? }
? ? ? ? ? ? @Override
? ? ? ? ? ? public String print(LocalDateTime object, Locale locale) {
? ? ? ? ? ? ? ? return DateTimeFormatter.ISO_DATE.format(object);
? ? ? ? ? ? }
? ? ? ? };
? ? }
}3.json請求時間戳轉換
本類型指在前端json請求,傳遞參數為時間戳,然后轉為LocalDateTime。
1.自定義解析注解
@Retention (RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
public @interface StampToLocalDateTime {
}2.自定義解析類
public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> ?{
? ? @Override
? ? public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException{
? ? ? ? if (StringUtils.isEmpty(jsonParser.getText())) {
? ? ? ? ? ? return null;
? ? ? ? }
? ? ? ? return Instant
? ? ? ? ? ? ? ? .ofEpochMilli(Long.parseLong(jsonParser.getText()))
? ? ? ? ? ? ? ? .atZone(ZoneOffset.ofHours(8))
? ? ? ? ? ? ? ? .toLocalDateTime();
? ? }
}在需要使用的字段添加@StampToLocalDateTime即可。示例如下
public class DemoReq ?{
?? ?
?? ?@StampToLocalDateTime
? ? private LocalDateTime signTime;
}4.序列化擴展
有時返回前端數據,要包裝下信息(比如返回全路徑地址及某些參數),直接硬編碼不夠優(yōu)雅。這時可以通過序列化操作,實現ContextualSerializer接口,要進行一些額外操作,。
1.自定義注解
@Retention (RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerializer(using = FullUrlSerializer.class)
public @interface FullUrl {
??? ?String value() default "";
}2.自定義序列類
public class FullUrlSerializer extends JsonSerializer<String> implements ContextualSerializer {
? ? private String params;
? ? @Value("${domain}")
? ? private String domain;
? ? public FullUrlSerializer() {
? ? }
? ? public FullUrlSerializer(String params) {
? ? ? ? this.params = params;
? ? }
? ? @Override
? ? public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
? ? ? ? if (property == null) {
? ? ? ? ? ? return prov.findNullValueSerializer(null);
? ? ? ? }
? ? ? ? if (Objects.equals(property.getType().getRawClass(), String.class)) {
? ? ? ? ? ? FullUrl fullUrl = property.getAnnotation(FullUrl.class);
? ? ? ? ? ? if (fullUrl == null) {
? ? ? ? ? ? ? ? fullUrl = property.getContextAnnotation(FullUrl.class);
? ? ? ? ? ? }
? ? ? ? ? ? if (fullUrl != null) {
? ? ? ? ? ? ? ? return new FullUrlSerializer(fullUrl.value());
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return prov.findValueSerializer(property.getType(), property);
? ? }
? ? @Override
? ? public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
? ? ? ? String url = "";
? ? ? ? if (!StringUtils.isEmpty(value)) {
? ? ? ? ? ? url = domain.concat(value);
? ? ? ? ? ? if (!StringUtils.isEmpty(params)) {
? ? ? ? ? ? ? ? url.contains(params);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? gen.writeString (url);
? ? }
}5.swagger支持
要使swagger支持LocalDateTime等類型可以設置directModelSubstitute,示例如下:
@Configuration
public abstract class SwaggerConfiguration {
?? ?@Bean
?? ?public Docket createRestApi() {
?? ??? ?return new Docket(DocumentationType.SWAGGER_2)
?? ??? ??? ??? ?.directModelSubstitute(LocalDateTime.class,String.class)
?? ??? ??? ??? ?.directModelSubstitute(LocalDate.class, String.class)
?? ??? ??? ??? ?.directModelSubstitute(LocalTime.class, String.class)
?? ??? ??? ??? ?.directModelSubstitute(ZonedDateTime.class,String.class)
?? ??? ??? ??? ?.build();
?? ?}
}以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- SpringBoot接收LocalDateTime參數的方式
- Springboot中LocalDateTime對象返回給前端格式化解決方案
- springboot中如何配置LocalDateTime JSON返回時間戳
- SpringBoot?LocalDateTime格式轉換方案詳解(前端入參)
- SpringBoot如何對LocalDateTime進行格式化并解析
- Springboot?格式化LocalDateTime的方法
- SpringBoot整合Mybatis?LocalDateTime?映射失效的解決
- springboot mybatis里localdatetime序列化問題的解決
- SpringBoot整合LocalDateTime的過程
相關文章
JAVA面試題 簡談你對synchronized關鍵字的理解
這篇文章主要介紹了JAVA面試題 請談談你對Sychronized關鍵字的理解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-07-07
SpringCloud集成Sleuth和Zipkin的思路講解
Zipkin 是 Twitter 的一個開源項目,它基于 Google Dapper 實現,它致力于收集服務的定時數據,以及解決微服務架構中的延遲問題,包括數據的收集、存儲、查找和展現,這篇文章主要介紹了SpringCloud集成Sleuth和Zipkin,需要的朋友可以參考下2022-11-11

