广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot 接收LocalDateTime方式
  • 721
分享到

springboot 接收LocalDateTime方式

2024-04-02 19:04:59 721人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录1.标准日期格式转换2.非JSON请求时间戳转换3.json请求时间戳转换4.序列化扩展5.swagger支持本文基于jdk8。 1.标准日期格式转换 本类型是指前端传递类似&q

本文基于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.序列化扩展

有时返回前端数据,要包装下信息(比如返回全路径地址及某些参数),直接硬编码不够优雅。这时可以通过序列化操作,实现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();
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: springboot 接收LocalDateTime方式

本文链接: https://www.lsjlt.com/news/153378.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作