简体   繁体   English

如何使用 Spring 和 Jackson 引导在没有纳秒的情况下序列化 Instant?

[英]How to serialize an Instant without nanoseconds using Spring Boot with Jackson?

Spring uses Jackson's InstantSerializer to write out my Instant fields like this: Spring 使用 Jackson 的 InstantSerializer 来写出我的 Instant 字段,如下所示:

now: "2021-04-07T10:51:53.043320Z"

I don't want the nanoseconds, though - just the milliseconds.不过,我不想要纳秒 - 只是毫秒。 I guessed that setting the application property我猜想设置应用程序属性

spring.jackson.serialization.write-date-timestamps-as-nanoseconds=false

would achieve this, but it makes no difference.会实现这一点,但这没有什么区别。

How can I tell Spring/Jackson to omit the nanoseconds when serializing Instants?我如何告诉 Spring/Jackson 在序列化 Instant 时省略纳秒?

(I'm using Spring Boot 2.2.11.RELEASE) (我正在使用 Spring 启动 2.2.11.RELEASE)

Update更新

I eventually got it work, based on this answer .基于这个答案,我最终得到了它的工作。 I had to use the deprecated JSR310Module instead of JavaTimeModule, and override the createContextual(...) method to force it to always use my serializer.我不得不使用已弃用的 JSR310Module 而不是 JavaTimeModule,并重写 createContextual(...) 方法以强制它始终使用我的序列化程序。

@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = builder.createXmlMapper(false).build();
    JSR310Module jsr310Module = new JSR310Module();
    jsr310Module.addSerializer(Instant.class, new MyInstantSerializer());
    objectMapper.registerModule(jsr310Module);
    return objectMapper;
}

private static class MyInstantSerializer extends InstantSerializer {
    public MyInstantSerializer() {
        super(InstantSerializer.INSTANCE, false, false, 
                new DateTimeFormatterBuilder().appendInstant(3).toFormatter());
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        return this;
    }
}

And this works too (based on Volodya's answer below ):这也有效(基于下面 Volodya 的回答):

@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomTimeSerialization() {
    return jacksonObjectMapperBuilder -> 
            jacksonObjectMapperBuilder.serializerByType(Instant.class, new JsonSerializer<Instant>() {

        private final DateTimeFormatter formatter = 
                new DateTimeFormatterBuilder().appendInstant(3).toFormatter();

        @Override
        public void serialize(
                Instant instant, JsonGenerator generator, SerializerProvider provider) throws IOException {
            generator.writeString(formatter.format(instant));
        }
    });
}

For that you could use @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS]")为此,您可以使用@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS]")

Full example:完整示例:

    import com.fasterxml.jackson.annotation.JsonFormat;
    import java.time.LocalDateTime;
    import java.time.ZonedDateTime;
    
    public class Message {
    
        @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS]")
        private final LocalDateTime dateTime;
    
        @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss[.SSS]")
        private final ZonedDateTime zonedDateTime;
    
        public Message(ZonedDateTime zonedDateTime) {
            this(zonedDateTime.toLocalDateTime(), zonedDateTime);
        }
    
        public Message(LocalDateTime dateTime, ZonedDateTime zonedDateTime) {
            this.dateTime = dateTime;
            this.zonedDateTime = zonedDateTime;
        }
    
        public LocalDateTime getDateTime() {
            return dateTime;
        }
    
        public ZonedDateTime getZonedDateTime() {
            return zonedDateTime;
        }
    }

Test:测试:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.json.JsonTest;
    import java.time.*;
    import java.time.temporal.ChronoUnit;
    import static org.junit.jupiter.api.Assertions.*;
    
    @JsonTest
    class MessageTest {
    
        @Autowired
        ObjectMapper mapper;
    
        @Test
        public void serializationTest() throws JsonProcessingException {
            final LocalDate date = LocalDate.of(2000, Month.JANUARY, 1);
            final LocalTime time = LocalTime.of(12, 20, 10).plus(123, ChronoUnit.MILLIS);
            final Message message = new Message(ZonedDateTime.of(date, time, ZoneId.systemDefault()));
    
            final String res = mapper.writeValueAsString(message);
    
            assertEquals("{\"dateTime\":\"2000-01-01T12:20:10.123\",\"zonedDateTime\":\"2000-01-01T12:20:10.123\"}", res);
        }
    
    }

Update:更新:

If you want to configure it centrally you could:如果您想集中配置它,您可以:

  1. Try to set the date format to your ObjectMapper as described here尝试将日期格式设置为您的 ObjectMapper,如此所述
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"));
  1. Customize your mapper like described here这里描述的那样自定义您的映射器
@SpringBootApplication
public class InstantSerializerApplication {

    public static void main(String[] args) {
        SpringApplication.run(InstantSerializerApplication.class, args);
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer addCustomTimeSerialization() {
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.serializerByType(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
            @Override
            public void serialize(ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                jsonGenerator.writeString(formatter.format(zonedDateTime));
            }
        });
    }
}

Better way of doing it is更好的方法是

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private final ZonedDateTime zonedDateTime;

For more info see the accepted answer for this question有关更多信息,请参阅此问题的已接受答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 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? 尝试使用 jackson 序列化 null Instant 时出错 - error trying to serialize null instant using jackson Spring 引导 Jackson 不序列化长时间戳 - Spring Boot Jackson does not serialize timestamps in Long Jackson 将 Instant 序列化为纳秒问题 - Jackson Serialize Instant to Nanosecond Issue 春季靴子+杰克逊。 如何将具有空值的集合序列化为空列表? - Spring boot + Jackson. How to serialize collections which have null value as empty lists? 如何使用杰克逊将此序列化为xml? - How to serialize this to xml using Jackson? 如何在 Spring 引导中序列化没有字段名称的请求 object? - How to serialize request object without field name in Spring Boot? Jackson / Spring Boot - 将 snake_case model 序列化为 camelCase - Jackson / Spring Boot - serialize a snake_case model to camelCase Spring引导2.04 Jackson无法将LocalDateTime序列化为String - Spring boot 2.04 Jackson cannot serialize LocalDateTime to String 在Spring Boot和ElasticSearch中使用Instant,LocalDateTime和ZonedDateTime - Using Instant, LocalDateTime and ZonedDateTime with Spring Boot and ElasticSearch
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM