[英]Spring Boot Jackson does not serialize timestamps in Long
I'm using Spring boot 2.3.1 version in my project.我在我的项目中使用 Spring boot 2.3.1 版本。 JDK version 11. I used Instant to return date.
JDK 版本 11。我使用 Instant 返回日期。 But I wanted to return date in Long, not in text format.
但我想以 Long 格式返回日期,而不是文本格式。 That's why I configured Jackson.
这就是我配置 Jackson 的原因。 But, Spring Boot generates timestamps in double instead of long.
但是,Spring Boot 会生成双精度时间戳,而不是长时间戳。 I configured Jackson in application.yml file with
我在 application.yml 文件中配置了 Jackson
jackson:
date-format: com.fasterxml.jackson.databind.util.ISO8601DateFormat
serialization:
write-dates-as-timestamps: on
deserialization:
read_date_timestamps_as_nanoseconds: on
time-zone: 'UTC'
But when receive timestamps in nanos they are not in Long type, They are in Double like=1593679103.899854000但是当在 nanos 中接收时间戳时,它们不是 Long 类型,它们是 Double like=1593679103.899854000
How can be fixed it?怎么能修好呢?
Spring's Jackson converts types by default. Spring 的 Jackson 默认转换类型。 In order to change type, conversions need to override the default configuration.
为了更改类型,转换需要覆盖默认配置。 The question above can be fixed by the following configuration.
上面的问题可以通过下面的配置来解决。
@Bean
public JavaTimeModule javaTimeModule() {
var javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(Instant.class, new InstantToLongSerializer());
return javaTimeModule;
}
static class InstantToLongSerializer extends JsonSerializer<Instant> {
@Override
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
gen.writeNumber(value.toEpochMilli());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.