How to set format of string for java.time.Instant using objectMapper?

后端 未结 7 845
失恋的感觉
失恋的感觉 2020-11-29 04:37

I have an entity with java.time.Instant for created data field:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public         


        
7条回答
  •  执笔经年
    2020-11-29 05:15

    Here's some Kotlin code of formatting Instant, so it does not contain milliseconds, you can use custom date formatters

    ObjectMapper().apply {
            val javaTimeModule = JavaTimeModule()
            javaTimeModule.addSerializer(Instant::class.java, Iso8601WithoutMillisInstantSerializer())
            registerModule(javaTimeModule)
            disable(WRITE_DATES_AS_TIMESTAMPS)
        }
    
    private class Iso8601WithoutMillisInstantSerializer
            : InstantSerializer(InstantSerializer.INSTANCE, false, DateTimeFormatterBuilder().appendInstant(0).toFormatter())
    

提交回复
热议问题