SpringCloud - Jackson序列化LocalDateTime

2021-06-17 19:51:32 浏览数 (1)

SpringCloud开发中,Jackson作为默认的序列化器,在跨服务调用过程中,序列化LocalDateTime时常发生格式不一致问题,下面将对SpringCloudJackson的序列化方式及源码进行分析。

专题参考:

Jackson - LocalDateTime序列化探索

1. 配置
  • maven
代码语言:javascript复制
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.9.RELEASE</version>
</parent>
<properties>
    <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
</properties>
2.反序列化
  • Controller
代码语言:javascript复制
@PostMapping("/test")
public SpuDetailDTO test(@RequestBody SpuDetailDTO spuDetailDTO) throws JsonProcessingException {
    System.out.println(spuDetailDTO);
    return spuDetailDTO;
}

@Data
public class SpuDetailDTO {
    private LocalDateTime updateTime;
}
  • Post请求Body 以下两种格式都支持
代码语言:javascript复制
{"updateTime": "2020-10-10T10:10:10"}
代码语言:javascript复制
{"updateTime": [2014, 10, 10, 10, 10, 10]}
  • Result Json 返回格式默认为yyyy-MM-ddTHH:mm:ss
代码语言:javascript复制
{"updateTime": "2020-10-10T10:10:10"}
3. 流程分析

在Spring启动的时候,会初始化JacksonObjectMapper,然后初始化JavaTimeModule,在JavaTimeModule中会默认加载LocalDateTime的序列化器(LocalDateTimeSerializer)和反序列化器(LocalDateTimeDeserializer),最终将JavaTimeModule注册到ObjectMapper中。

  • LocalDateTimeDeserializer 反序列化支持yyyy-MM-ddTHH:mm:ssyyyy-MM-ddTHH:mm:ss的格式。
  • LocalDateTimeSerializer 序列化默认使用yyyy-MM-ddTHH:mm:ss格式。

流程如下:

至此之后,所有的Controller接口的调用,或者Feign调用LocalDateTime的序列化和反序列化,都会使用该配置。

5. 源码分析
  • MappingJackson2HttpMessageConverter.MappingJackson2HttpMessageConverter()
代码语言:javascript复制
public class MappingJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {

    ...
    public MappingJackson2HttpMessageConverter() {
        // TODO: 初始化
        this(Jackson2ObjectMapperBuilder.json().build());
    }
  • Jackson2ObjectMapperBuilder.build()
代码语言:javascript复制
public class Jackson2ObjectMapperBuilder {
    ....
    public <T extends ObjectMapper> T build() {
        ObjectMapper mapper;
        // TODO: 初始化ObjectMapper
        if (this.createXmlMapper) {
            mapper = (this.defaultUseWrapper != null ?
                    new XmlObjectMapperInitializer().create(this.defaultUseWrapper, this.factory) :
                    new XmlObjectMapperInitializer().create(this.factory));
        }
        else {
            mapper = (this.factory != null ? new ObjectMapper(this.factory) : new ObjectMapper());
        }
        // TODO: 配置mapper
        configure(mapper);
        return (T) mapper;
    }
  • Jackson2ObjectMapperBuilder.configure()
代码语言:javascript复制
public class Jackson2ObjectMapperBuilder {
    public void configure(ObjectMapper objectMapper) {
        Assert.notNull(objectMapper, "ObjectMapper must not be null");

        MultiValueMap<Object, Module> modulesToRegister = new LinkedMultiValueMap<>();
        if (this.findModulesViaServiceLoader) {
            ObjectMapper.findModules(this.moduleClassLoader).forEach(module -> registerModule(module, modulesToRegister));
        }
        else if (this.findWellKnownModules) {
            // TODO: 注册 Module
            registerWellKnownModulesIfAvailable(modulesToRegister);
        }
代码语言:javascript复制
public class Jackson2ObjectMapperBuilder {
...
private void registerWellKnownModulesIfAvailable(MultiValueMap<Object, Module> modulesToRegister) {
    
    // jackson-datatype-jdk8
    ...

    try {
        Class<? extends Module> javaTimeModuleClass = (Class<? extends Module>)
                ClassUtils.forName("com.fasterxml.jackson.datatype.jsr310.JavaTimeModule", this.moduleClassLoader);
        // TODO: 默认加载jsr310的JavaTimeModule
        Module javaTimeModule = BeanUtils.instantiateClass(javaTimeModuleClass);
        modulesToRegister.set(javaTimeModule.getTypeId(), javaTimeModule);
    }
    catch (ClassNotFoundException ex) {
        // jackson-datatype-jsr310 not available
    }

    // Joda-Time present?
    ...
    // Kotlin present?
    ...
    }
}
  • JavaTimeModule无参构造函数
代码语言:javascript复制
public final class JavaTimeModule extends SimpleModule
{
    ...
    public JavaTimeModule()
    {
        ...
        // TODO: 反序列化
        addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);
        addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE);
        addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE);
        ...
        // TODO: 序列化
        addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE);
        addSerializer(LocalDate.class, LocalDateSerializer.INSTANCE);
        addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE);
        ...
    }

LocalDateDeserializer.INSTANCE支持yyyy-MM-ddTHH:mm:ss[yyyy, MM, dd, HH, mm, ss]格式的反序列化。 LocalDateTimeSerializer.INSTANCE也支持yyyy-MM-ddTHH:mm:ss[yyyy, MM, dd, HH, mm, ss]的序列化。但是在Spring中,JacksonAutoConfigurationSerializationFeature默认加载的WRITE_DATES_AS_TIMESTAMPSWRITE_DURATIONS_AS_TIMESTAMPS置为false,导致仅支持format格式的输出。 源码如下:

  • JacksonAutoConfiguration - Jackson配置
代码语言:javascript复制
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
public class JacksonAutoConfiguration {

    private static final Map<?, Boolean> FEATURE_DEFAULTS;

    static {
        Map<Object, Boolean> featureDefaults = new HashMap<>();
        // TODO: 设置为false
    featureDefaults.put(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        // TODO: 设置为false
        featureDefaults.put(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
        FEATURE_DEFAULTS = Collections.unmodifiableMap(featureDefaults);
    }
  • SerializationFeature - 序列化器功能
代码语言:javascript复制
public enum SerializationFeature implements ConfigFeature
{
    ...
    WRITE_DATES_AS_TIMESTAMPS(true), // TODO: 默认为true
    ...
    WRITE_DURATIONS_AS_TIMESTAMPS(true),// TODO: 默认为true
    ...
  • LocalDateTimeSerializer - LocalDateTime序列化
代码语言:javascript复制
public class LocalDateTimeSerializer extends JSR310FormattedSerializerBase<LocalDateTime>
{
    @Override
    public void serialize(LocalDateTime value, JsonGenerator g, SerializerProvider provider)
        throws IOException
    {
        // TODO: 如果使用 WRITE_DATES_AS_TIMESTAMPS 特性,并且format为空, 
        // 则序列化为[yyyy, MM, dd, HH, mm, ss]
        if (useTimestamp(provider)) {
            g.writeStartArray();
            _serializeAsArrayContents(value, g, provider);
            g.writeEndArray();
        } else {
            DateTimeFormatter dtf = _formatter;
            if (dtf == null) {
                dtf = _defaultFormatter();
            }
            g.writeString(value.format(dtf));
        }
    }

    protected boolean useTimestamp(SerializerProvider provider) {
        if (_useTimestamp != null) {
            return _useTimestamp.booleanValue();
        }
        if (_shape != null) {
            if (_shape == Shape.STRING) {
                return false;
            }
            if (_shape == Shape.NUMBER_INT) {
                return true;
            }
        }
        // assume that explicit formatter definition implies use of textual format
        // TODO: 是否设置 WRITE_DATES_AS_TIMESTAMPS 并且format为空
        return (_formatter == null) && (provider != null)
                && provider.isEnabled(getTimestampsFeature());
    }
6. 结论

SpringCloud中对于LocalDateTime,Jackson默认使用jackson-datatype-jsr310JavaTimeModule进行序列化和反序列化配置,JacksonAutoConfiguration对序列化格式进行了调整,不采用数组的形式进行序列化,而采用format的形式。 最终通过 LocalDateTimeDeserializerdeserialize实现反序列化,默认支持yyyy-MM-ddTHH:mm:ss[yyyy, MM, dd, HH, mm, ss]格式。 LocalDateTimeSerializerserialize实现序列化,默认支持yyyy-MM-ddTHH:mm:ss格式。

7. 其他参考
  1. Spring Boot升级到2.x,Jackson对Date时间类型序列化的变化差点让项目暴雷
  2. SpringBoot2.X中spring.jackson.date-format失效的解决办法

0 人点赞