简体   繁体   English

Spring 引导 Jackson 不序列化长时间戳

[英]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.

相关问题 Spring引导2.04 Jackson无法将LocalDateTime序列化为String - Spring boot 2.04 Jackson cannot serialize LocalDateTime to String 如何使用 Spring 和 Jackson 引导在没有纳秒的情况下序列化 Instant? - How to serialize an Instant without nanoseconds using Spring Boot with Jackson? LocalDateTime 不显示为时间戳(即长) java 8 spring 引导 2.2.0 - LocalDateTime not displaying as timestamps (ie as a long) java 8 spring boot 2.2.0 如何在 YAML 文件中配置 WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS 用于 Spring Boot 中的 Jackson 反序列化? - How to configure WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS in YAML file for Jackson deserialization in Spring Boot? 在春季启动时反序列化杰克逊 - Deserialize jackson in spring boot 春季靴子杰克逊与日期 - Spring boot Jackson with Date 当序列化有条件地跳过符合 Jackson 自定义标准的对象时修改 HTTP 代码(Spring 启动) - Modify HTTP code when Serialize skipping objects conditionally that meet a Custom Criteria with Jackson (Spring boot) Spring Boot + Jackson:根据所调用的REST API以不同的方式序列化对象 - Spring Boot + Jackson: Serialize an object in different ways depending on the called REST API 春季靴子+杰克逊。 如何将具有空值的集合序列化为空列表? - Spring boot + Jackson. How to serialize collections which have null value as empty lists? Spring Boot 序列化 JSON - Spring Boot Serialize JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM