繁体   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