java - 是否可以简化 @JsonSerialize 注释?
问题描述
以下代码工作正常:
// 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();
}
有什么想法我可以尝试吗?
解决方案
如果您使用 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;
}
推荐阅读
- r - 当所有括号看起来都匹配时,R中的“不匹配的左括号”错误
- react-native - 你能把一个对象放在一个数组中,而这个数组又在另一个对象中吗?
- javascript - 如何在反应中将外部样式表应用于 iframe 子组件
- c# - 我必须创建随机数骰子
- javascript - 如何直接从异步函数返回对象?
- forms - 如何从 Drupal 8 中的“select2”类型的多个字段中检索数据
- mysql - DDEV 通过 SSH 隧道从登台服务器连接到 MySQL 数据库返回:无法分配请求的地址
- python - 如何修复 TypeError:只能将列表(而不是“str”)连接到列表?
- c++ - 带类的动态分配
- ios - iPhone 12 Pro 上的 AVFoundation depthData.depthDataMap 有时为空