是否可以简化@JsonSerialize注释?

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

以下代码工作正常:

    // 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"])

弹簧应用的配置扩展为:

@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();
  }

我有什么想法可以尝试吗?

java datetime jackson-databind jsonserializer localdate
2个回答
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
投票

这将使用LocalDateTimeSerializer / LocalDateTimeDeserializer序列化/反序列化整个MyClass,而不是它的时间字段。

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

相反,你可以将JavaTimeModule注册到你的ObjectMapper

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