SpringCloud开发中,Jackson作为默认的序列化器,在跨服务调用过程中,序列化LocalDateTime
时常发生格式不一致问题,下面将对SpringCloud中Jackson的序列化方式及源码进行分析。
专题参考:
1. 配置
- maven
<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
@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
以下两种格式都支持
{"updateTime": "2020-10-10T10:10:10"}
{"updateTime": [2014, 10, 10, 10, 10, 10]}
- Result Json
返回格式默认为yyyy-MM-ddTHH:mm:ss
{"updateTime": "2020-10-10T10:10:10"}
3. 流程分析
在Spring启动的时候,会初始化Jackson
的ObjectMapper
,然后初始化JavaTimeModule
,在JavaTimeModule
中会默认加载LocalDateTime
的序列化器(LocalDateTimeSerializer
)和反序列化器(LocalDateTimeDeserializer
),最终将JavaTimeModule
注册到ObjectMapper
中。
-
LocalDateTimeDeserializer
反序列化支持yyyy-MM-ddTHH:mm:ss
和yyyy-MM-ddTHH:mm:ss
的格式。 -
LocalDateTimeSerializer
序列化默认使用yyyy-MM-ddTHH:mm:ss
格式。
流程如下:
至此之后,所有的Controller接口的调用,或者Feign调用LocalDateTime
的序列化和反序列化,都会使用该配置。
5. 源码分析
- MappingJackson2HttpMessageConverter.MappingJackson2HttpMessageConverter()
public class MappingJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {
...
public MappingJackson2HttpMessageConverter() {
// TODO: 初始化
this(Jackson2ObjectMapperBuilder.json().build());
}
- Jackson2ObjectMapperBuilder.build()
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()
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);
}
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无参构造函数
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中,JacksonAutoConfiguration
将SerializationFeature
默认加载的WRITE_DATES_AS_TIMESTAMPS
和WRITE_DURATIONS_AS_TIMESTAMPS
置为false
,导致仅支持format格式的输出。
源码如下:
- JacksonAutoConfiguration - Jackson配置
@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 - 序列化器功能
public enum SerializationFeature implements ConfigFeature
{
...
WRITE_DATES_AS_TIMESTAMPS(true), // TODO: 默认为true
...
WRITE_DURATIONS_AS_TIMESTAMPS(true),// TODO: 默认为true
...
- LocalDateTimeSerializer - LocalDateTime序列化
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-jsr310
的JavaTimeModule
进行序列化和反序列化配置,JacksonAutoConfiguration
对序列化格式进行了调整,不采用数组的形式进行序列化,而采用format的形式。
最终通过
LocalDateTimeDeserializer
的deserialize
实现反序列化,默认支持yyyy-MM-ddTHH:mm:ss
和[yyyy, MM, dd, HH, mm, ss]
格式。
LocalDateTimeSerializer
的serialize
实现序列化,默认支持yyyy-MM-ddTHH:mm:ss
格式。
网友评论