1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
@Slf4j @Configuration public class JacksonCustomizerConfig {
@Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}") private String localDateTimePattern;
@Value("${spring.jackson.local-date-format:yyyy-MM-dd}") private String localDatePattern;
@Value("${spring.jackson.local-time-format:HH:mm:ss}") private String localTimePattern;
@Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> { builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(localDateTimePattern))); builder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(localDatePattern))); builder.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(localTimePattern))); builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(localDateTimePattern))); builder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(localDatePattern))); builder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(localTimePattern))); }; }
@Component public static class LocalDateTimeConverter implements Converter<String, LocalDateTime> { @Override public LocalDateTime convert(String source) { if (StringUtils.isBlank(source)) { return null; } if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) { return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); } throw new IllegalArgumentException("Invalid value '" + source + "'"); } }
@Component public static class LocalDateConverter implements Converter<String, LocalDate> { @Override public LocalDate convert(String source) { if (StringUtils.isBlank(source)) { return null; } if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) { return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd")); } throw new IllegalArgumentException("Invalid value '" + source + "'"); } } }
|