是否可以简化@JsonSerialize注释?

时间:2019-04-23 12:15:23

标签: java datetime jackson-databind jsonserializer localdate

以下代码可以正常工作:

    // works
public class MyClass {

  @JsonSerialize(using = LocalDateTimeSerializer.class)
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  private LocalDateTime startDate;

  @JsonSerialize(using = LocalDateTimeSerializer.class)
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  private LocalDateTime endDate;

  @JsonSerialize(using = LocalDateTimeSerializer.class)
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  private LocalDateTime otherDate;

  @JsonSerialize(using = LocalDateTimeSerializer.class)
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  private LocalDateTime someMoreDate;

...}

但是我不喜欢为每个Date字段编写完全相同的注释的重复方面。

我尝试过的事情:

// does not work

  @JsonSerialize(using = LocalDateTimeSerializer.class)
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
public class MyClass {


  private LocalDateTime startDate;
  private LocalDateTime endDate;
  private LocalDateTime otherDate;
  private LocalDateTime someMoreDate;

...}

尝试此操作会导致错误:

Caused by: com.fasterxml.jackson.databind.JsonMappingException: 
class MyClass cannot be cast to class java.time.LocalDateTime (MyClass is in unnamed module of loader 'app'; java.time.LocalDateTime is in module java.base of loader 'bootstrap') (through reference chain: java.util.HashMap["ctxData"])

spring应用程序的配置通过以下方式扩展:

@Bean(name = "OBJECT_MAPPER_BEAN")
  public ObjectMapper jsonObjectMapper() {
    return Jackson2ObjectMapperBuilder.json()
        .serializationInclusion(JsonInclude.Include.NON_NULL)
        .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        .modules(new JavaTimeModule())
        .build();
  }

有什么想法可以尝试吗?

2 个答案:

答案 0 :(得分:2)

如果您正在使用jackson通过Spring管理json序列化/反序列化,则可以全局配置ObjectMapper

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();

    builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ISO_DATE_TIME));
    builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));

    return builder;
}

答案 1 :(得分:1)

这将使用LocalDateTimeSerializer / LocalDateTimeDeserializer对整个MyClass(而不是其时间字段)进行序列化/反序列化。

@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
public class MyClass {

相反,您只需将JavaTimeModule注册到您的ObjectMapper