栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LocalDateTime作为入参和返参的序列化问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LocalDateTime作为入参和返参的序列化问题

我们都知道LocalDatetime、LocalDate以及LocalTime,是JDK8 新增的和时间相关的类。在SpringBoot的创建接口的时候,可能需要将Local的相关时间类作为参数,但是有时候需要特输的时间格式,由于SpringBoot默认使用Jackson作为序列化的框架,所以在配置LocalDatetime这类新的API的时候,默认的参数就非常得让人不爽。经过一段折腾,笔者找到合适的解决方法,这里提供了一个简单地方法,将相应的时间转换为ISO8601的时间格式,保存了时区信息,同时接受参数也可以包含时区信息,或者自定义为前端需要的格式。

主要的点就是:
  1. 配置一些Bean用于将字符串转换为LocalDatetime类,也就是反序列化的配置
  2. 配置ObjectMapper,用户序列化的配置
依赖

Maven



    com.fasterxml.jackson.datatype
    jackson-datatype-jsr310
    2.9.8

代码如下

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;


@Configuration
public class LocalDateTimeSerializerConfig {

  
  @Bean
  public Converter localDateConverter() {
    return new Converter() {
      @Override
      public LocalDate convert(@NotNull String source) {
        if (StringUtils.hasText(source)) {
          return LocalDate.parse(source, DateTimeFormatter.ISO_OFFSET_DATE);
        }
        return null;
      }
    };
  }

  
  @Bean
  public Converter localDateTimeConverter() {
    return new Converter() {
      @Override
      public LocalDateTime convert(@NotNull String source) {
        if (StringUtils.hasText(source)) {
          return LocalDateTime.parse(source, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        }
        return null;
      }
    };
  }

  
  @Bean
  public Converter localTimeConverter() {
    return new Converter() {
      @Override
      public LocalTime convert(@NotNull String source) {
        if (StringUtils.hasText(source)) {
          return LocalTime.parse(source, DateTimeFormatter.ISO_OFFSET_TIME);
        }
        return null;
      }
    };
  }

  
  @Bean
  public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

    // LocalDateTime系列序列化模块,继承自jsr310,我们在这里修改了日期格式
    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(
        LocalDateTime.class,
        new JsonSerializer() {
          @Override
          public void serialize(
              LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
              throws IOException {
            String format =
                value.atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            gen.writeString(format);
          }
        });

    javaTimeModule.addSerializer(
        LocalDate.class,
        new JsonSerializer() {
          @Override
          public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers)
              throws IOException {
            String format = value.format(DateTimeFormatter.ISO_OFFSET_DATE);
            gen.writeString(format);
          }
        });

    objectMapper.registerModule(javaTimeModule);
    return objectMapper;
  }
}

代码很简单, 这里不再赘述,稍微看下就明白了了,需要注意的是:

  1. Converter 实现的时候 不要简写为Lambda表达式,会报错,这是因为丢失类型信息导致的转换失败;
  2. 这里仅仅实现了我自己的需要的转换关系,若是没有需要,可以尝试对应写一下;
  3. 一定要保证这个类被扫描到;
  4. 各个实现的逻辑不通,可以自己根据自己的需求实现。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1021620.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号