是否可以简化 @JsonSerialize 注释?
Posted
技术标签:
【中文标题】是否可以简化 @JsonSerialize 注释?【英文标题】:Is it possible to simplify @JsonSerialize annotations? 【发布时间】:2019-09-12 15:04:26 【问题描述】:以下代码可以正常工作:
// 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;
...
但我不喜欢为每个日期字段编写完全相同的注释的重复方面。
我尝试了什么:
// 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();
有什么我可以尝试的想法吗?
【问题讨论】:
对于java.time
的东西,您只需将一个模块添加到您的ObjectMapper,然后您就不需要任何注释objectMapper.registerModule(new JavaTimeModule());
我在spring应用的配置中添加了上面的bean。这是正确的吗?
【参考方案1】:
如果你使用 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;
【讨论】:
我喜欢这种方法,但似乎我还没有正确的设置。如果我删除字段注释并定义全局映射器,它就不再起作用了【参考方案2】:这将使用LocalDateTimeSerializer
/LocalDateTimeDeserializer
序列化/反序列化整个MyClass
,而不是它的时间字段。
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
public class MyClass
相反,您可以将JavaTimeModule
注册到您的ObjectMapper
。
【讨论】:
我可以在@Bean 中进行注册调用吗?以上是关于是否可以简化 @JsonSerialize 注释?的主要内容,如果未能解决你的问题,请参考以下文章
JsonSerialize的字段[include]已经过时,已被JsonInclude代替