簡體   English   中英

將 Instant 轉換為 ISO8601 日期格式在 Spring Boot 中不起作用

[英]Convert Instant to ISO8601 date format not working in Spring Boot

我正在使用 spring boot 2.3.4.RELEASE 並且當嘗試將包含 Instant 屬性的 DTO 轉換為 JSON 格式時,jackson ObjectMapper 繼續將其轉換為時間戳格式,即使關閉了 write-dates-as-timestamps 選項。

pom.xml

<parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.3.4.RELEASE</version>
     <relativePath/> <!-- lookup parent from repository -->
</parent> 

....

<dependency>
     <groupId>com.fasterxml.jackson.datatype</groupId>
     <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

應用程序屬性

spring.jackson.serialization.write-dates-as-timestamps = false

DTO:

@Data
public class MyDTO {

    Long id;

    @NotNull
    String number;

    @NotNull
    Integer year;

    @NotNull
    VesselContractStatusEnum status;

    Instant statusDate;
}

休息控制器響應:

{
    "id": 1,
    "number": "202000",
    "year": 2020,
    "status": "Open",
    "statusDate": 1602298800
 }

按照 StackOverflow 中的建議,我嘗試使用以下方法覆蓋 ObjectMapper,但沒有奏效。

@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {

    ObjectMapper objectMapper = builder.build();

    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    JavaTimeModule javaTimeModule = new JavaTimeModule();
    objectMapper.registerModule(javaTimeModule);
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));

    return objectMapper;
}

Instant.toString()返回 ISO8601 格式的字符串(它的價值)。 也許為 Json 領域提供一個吸氣劑會有所幫助?

您必須編寫自定義序列化器和 De Serializer 類,如下所示:

序列化器類:

public class InstantSerializer extends JsonSerializer<Instant> {

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneOffset.UTC);

    @Override
    public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        String str = dateTimeFormatter.format(instant);

        jsonGenerator.writeString(str);
    }
}

解串器類:

public class InstantDeserializer extends JsonDeserializer<Instant> {

    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneOffset.UTC);

    @Override
    public Instant deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return Instant.from(dateTimeFormatter.parse(jsonParser.getText()));
    }
}

然后在 DTO 類中的 Instant 變量頂部添加以下注釋,如下所示:

@JsonDeserialize(using = InstantDeserializer.class)
@JsonSerialize(using = InstantSerializer.class)
Instant statusDate;

你有注釋嗎

@EnableWebMvc

任何地方?

在嘗試了一切都沒有成功之后,我通過刪除主類上的@EnableWebMvc 注釋(用@SpringBootApplication 注釋)來讓它工作。

我認為@EnableWebMvc 接管了所有 MVC 配置控制。
如果你真的需要@EnableWebMvc,那么你必須手動注冊序列化器/反序列化器。 例如。 通過在主類中添加類似的東西(用@SpringBootApplication 注釋):

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
  {
    SimpleModule m = new SimpleModule();
    m.addSerializer(Instant.class, new MyCustomJsonSerializer());
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder().modules(m);
    converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM