SpringBoot in LocalDatetime as parameter and return value serialization problems

Welcome to my personal website https://www.zhoutao123.com , paper original address https://www.zhoutao123.com/#/blog/article/59

LocalDatetime, LocalDate and LocalTime, is JDK8 new class and time dependent. In creating an interface when SpringBoot may need to be relevant Local time class as an argument, but sometimes need special time format to lose, because the default SpringBoot Jackson as a sequence of frames, so this type of configuration LocalDatetime new API's when the default parameters have to make people very uncomfortable. After a period of agonizing, I find a suitable solution, there is provided a simple method to convert the appropriate time is the time in ISO8601 format, saving the time zone information, while receiving the parameter may comprise time zone information, or customize a front end needs format.

Ps: Of course you can use @JsonFormat and other annotations logo, but the process can be unified why a single add so much trouble?

The main point is this:

  • [X] is used to configure some Bean string into LocalDatetime type, i.e. arranged deserialized
  • [X] configured ObjectMapper, user configuration serialized

I suggest, create a user named LocalDatetimConfig.java class centralized configuration in the project.

rely

  • grale
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.8'
  • Maven
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.9.8</version>
</dependency>

code show as below

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;

/** Converter 不可优化使用Lambda表达式,否则会出现启动失败的问题 */
@Configuration
public class LocalDateTimeSerializerConfig {

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

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

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

  /** Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json */
  @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<LocalDateTime>() {
          @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<LocalDate>() {
          @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;
  }
}

The code is simple, not repeat them here, a little look to understand, and to note that:

  • [X] Converter <String, LocalDateTime> do not realize when abbreviated as Lambda expressions, will complain that this is the type of conversion failed because of loss of information caused.
  • [X] here only to realize my own conversion relationship needs, if not necessary, try a corresponding write about
  • [X] must be scanned to ensure that the class
  • Logic [x] various implementations of the barrier, can be implemented according to their own needs

Guess you like

Origin www.cnblogs.com/zhoutao825638/p/11767906.html