LocalDate 被序列化为数组

问题描述 投票:0回答:3

我正在使用 springBoot 开发 REST APi。我在 GET 端点的响应模型中有一个 LocalDate 字段“firstDate”。但是这个 LocalDate 可以在响应的 json 中序列化为数组!

"firstDate": [
        2021,
        3,
        1
      ],

因此,为了使用这个 APi,我必须在 DTO 中将这个日期定义为数组!这不好! 我的 API 响应模型是用 swagger 生成的,所以我不能使用 @JsonFormat(pattern="yyyy-MM-dd")

您能帮助我并告诉我在这种情况下如何正确序列化 LocalDate 吗?

非常感谢。

arrays json spring-boot jackson localdate
3个回答
3
投票

我定义为 LocalDateTime 的日期被序列化为这样的数组:

"timestamp": [
    2023,
    2,
    15,
    10,
    30,
    45,
    732425200
],

这就是我在 WebConfig.java 中所做的:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

  // other configs

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    WebMvcConfigurer.super.extendMessageConverters(converters);
    converters.add(new MappingJackson2HttpMessageConverter(
        new Jackson2ObjectMapperBuilder()
            .dateFormat(new StdDateFormat())
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .build()));
  }

}

现在一切都好起来了:

"timestamp": "2023-02-15T10:32:06.5170689",

希望对您有所帮助。一些帮助我实现这一目标的主题:

在 Spring Rest API 中配置 LocaldateTime

如何自定义 Spring Boot 隐式使用的 Jackson JSON 映射器?

无法使用 Jackson 将 java.time.LocalDate 序列化为字符串


2
投票

我认为这个WebConfig.class是不必要的。您可以在您的领域尝试类似的方法firstDate:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private LocalDate firstDate;

由于 swagger 配置,在 DTO 中将字段定义为数组是没有意义的


0
投票

为日期字段设置反序列化器和序列化器将解决问题:

@JsonSerialize(using = LocalDateSerializer.class)
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate issueDate;

使用

LocalDateTimeSerializer
表示
LocalDateTime
字段

© www.soinside.com 2019 - 2024. All rights reserved.