springboot接收LocalDateTime的方式是什么

发布时间:2022-07-05 11:48:56 作者:iii
来源:亿速云 阅读:856

本文小编为大家详细介绍“springboot接收LocalDateTime的方式是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“springboot接收LocalDateTime的方式是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

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();
    }
}

读到这里,这篇“springboot接收LocalDateTime的方式是什么”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. springboot 启动接收参数
  2. 详解SpringBoot Controller接收参数的几种常用方式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot localdatetime

上一篇:基于Qt OpenCV怎么实现图像灰度化像素

下一篇:PyTorch中的nn.Embedding怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》