java-是否可以简化@JsonSerialize注释?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-是否可以简化@JsonSerialize注释?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2093字,纯文字阅读大概需要3分钟。
内容图文
以下代码可以正常工作:
// 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;
}
内容总结
以上是互联网集市为您收集整理的java-是否可以简化@JsonSerialize注释?全部内容,希望文章能够帮你解决java-是否可以简化@JsonSerialize注释?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。