【问题标题】:LocalDate Serialization: date as array?LocalDate 序列化:日期为数组?
【发布时间】:2020-03-30 07:31:09
【问题描述】:

我使用 Java 11 并希望将 LocalDate/LocalDateTime 序列化/反序列化为字符串。 好的。 我添加了依赖:

    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
        <version>${jackson.version}</version>
    </dependency>

和模块:

@Bean
public ObjectMapper objectMapper() {
    return new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
}

当我向我的应用发送日期时,它会正确反序列化:

{"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}

当我直接使用 objectMapper 作为 bean 时,它也可以正确序列化:

{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":"2008-03-20","relativeType":"SON","cohabitants":true}

但是当它用控制器序列化时,它序列化为数组:

{"code":"SUCCESS","id":868,"profileId":12608,"birthDate":[2008,3,20],"relativeType":"SON","cohabitants":true}

问题是反序列化控制器正文中的日期。 控制器是:

@PostMapping
public Relative create(@Validated(Validation.Create.class) @RequestBody Relative relative) {
    return service.create(relative);
}

Relative.class:

@Getter
@Setter
@ToString(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Relative extends MortgageResponse {

    @Null(groups = Validation.Create.class)
    @NotNull(groups = Validation.Update.class)
    private Long id;

    @NotNull
    private Long profileId;

    private LocalDate birthDate;
    private RelativeType relativeType;
    private Boolean cohabitants;
}

请告诉我,有什么问题以及如何解决它。

【问题讨论】:

  • 也添加您的相对类
  • 完成,添加类

标签: java spring objectmapper


【解决方案1】:

@JsonFormat 注释 添加到您的birthDate 字段,或者更确切地说是任何日期字段,并且您的 ObjectMapper(Spring Boot 与否)应该尊重格式,只要您对您的文件有额外的 js310 依赖类路径。

@JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthDate;

【讨论】:

    猜你喜欢
    • 2018-12-13
    • 2021-05-27
    • 2020-10-06
    • 2019-06-15
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多