一、 引用依赖
<dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>7.2.0</version> </dependency>
二、自定义序列化类
package com.vteam.uap.serializer; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import java.io.IOException; import java.time.DateTimeException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * @author Miller.Lai * @description: LocalDateTime自定义序列化 * @date 2023-12-21 13:26:47 */ public class CustomLocalDateTimeDeserializer extends LocalDateTimeDeserializer { public CustomLocalDateTimeDeserializer(DateTimeFormatter formatter) { super(formatter); } @Override public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException { if (parser.hasTokenId(6)) { return this._fromString(parser, context, parser.getText()); } else if (parser.isExpectedStartObjectToken()) { return this._fromString(parser, context, context.extractScalarFromObject(parser, this, this.handledType())); } else { if (parser.isExpectedStartArrayToken()) { JsonToken t = parser.nextToken(); if (t == JsonToken.END_ARRAY) { return null; } LocalDateTime result; if ((t == JsonToken.VALUE_STRING || t == JsonToken.VALUE_EMBEDDED_OBJECT) && context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) { result = this.deserialize(parser, context); if (parser.nextToken() != JsonToken.END_ARRAY) { this.handleMissingEndArrayForSingle(parser, context); } return result; } if (t == JsonToken.VALUE_NUMBER_INT) { int year = parser.getIntValue(); int month = parser.nextIntValue(-1); int day = parser.nextIntValue(-1); int hour = parser.nextIntValue(-1); int minute = parser.nextIntValue(-1); t = parser.nextToken(); if (t == JsonToken.END_ARRAY) { result = LocalDateTime.of(year, month, day, hour, minute); } else { int second = parser.getIntValue(); t = parser.nextToken(); if (t == JsonToken.END_ARRAY) { result = LocalDateTime.of(year, month, day, hour, minute, second); } else { int partialSecond = parser.getIntValue(); if (partialSecond < 1000 && !context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { partialSecond *= 1000000; } if (parser.nextToken() != JsonToken.END_ARRAY) { throw context.wrongTokenException(parser, this.handledType(), JsonToken.END_ARRAY, "Expected array to end"); } result = LocalDateTime.of(year, month, day, hour, minute, second, partialSecond); } } return result; } context.reportInputMismatch(this.handledType(), "Unexpected token (%s) within Array, expected VALUE_NUMBER_INT", new Object[]{t}); } if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) { return (LocalDateTime)parser.getEmbeddedObject(); } else { if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) { this._throwNoNumericTimestampNeedTimeZone(parser, context); } return (LocalDateTime)this._handleUnexpectedToken(context, parser, "Expected array or string.", new Object[0]); } } } @Override protected LocalDateTime _fromString(JsonParser p, DeserializationContext ctxt, String string0) throws IOException { String string = string0.trim(); DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; if (string.length() == 0) { return (LocalDateTime)this._fromEmptyString(p, ctxt, string); } else { try { if (formatter == DateTimeFormatter.ISO_LOCAL_DATE_TIME && string.length() > 10 && string.charAt(10) == 'T' && string.endsWith("Z")) { if (this.isLenient()) { return LocalDateTime.parse(string.substring(0, string.length() - 1), formatter); } else { JavaType t = this.getValueType(ctxt); return (LocalDateTime)ctxt.handleWeirdStringValue(t.getRawClass(), string, "Should not contain offset when 'strict' mode set for property or type (enable 'lenient' handling to allow)", new Object[0]); } } else { return convert(string); } } catch (DateTimeException var6) { return (LocalDateTime)this._handleDateTimeException(ctxt, var6, string); } } } public LocalDateTime convert(String source) { source = source.trim(); if ("".equals(source)) { return null; } if (source.matches("^\\d{4}-\\d{1,2}$")) { // yyyy-MM return LocalDate.parse(source+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay(); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) { // yyyy-MM-dd return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay(); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) { // yyyy-MM-dd HH:mm return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) { // yyyy-MM-dd HH:mm:ss return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); } else { throw new IllegalArgumentException("Invalid datetime value '" + source + "'"); } } }
三、添加配置类
package com.vteam.ipu.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.vteam.uap.serializer.CustomLocalDateTimeDeserializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * @author Miller.Lai * @description: 自定义LocalDateTime的序列化方式 * @date 2023-12-20 16:41:33 */ @Configuration public class DateSerializerConfig { @Bean public ObjectMapper serializingObjectMapper() { JavaTimeModule javaTimeModule = new JavaTimeModule(); CustomLocalDateTimeDeserializer dateTimeDeserializer = new CustomLocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); LocalDateTimeSerializer dateTimeSerializer = new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); javaTimeModule.addDeserializer(LocalDateTime.class, dateTimeDeserializer); javaTimeModule.addSerializer(LocalDateTime.class, dateTimeSerializer); LocalDateDeserializer localDateDeserializer = new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDateSerializer localDateSerializer = new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")); javaTimeModule.addDeserializer(LocalDate.class, localDateDeserializer); javaTimeModule.addSerializer(LocalDate.class, localDateSerializer); return Jackson2ObjectMapperBuilder.json().modules(javaTimeModule) .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).build(); } }
本人近十年JAVA架构设计经验,长期从事IT技术资源整合。有志于自我技术提升、需要最新IT技术课程的小伙伴,可私信联系我 ,粉丝一律友情价