杰克逊转换LocalDatetime [英] Jackson converting LocalDatetime

查看:88
本文介绍了杰克逊转换LocalDatetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个@JsonFormat的LocalDateTime字段

I've a LocalDateTime field with @JsonFormat

@JsonFormat(pattern = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'")
private LocalDateTime dateTime;

当Jackson尝试解析诸如 2018-11-28T15:24:00.000Z 之类的日期时,会抛出异常

When Jackson try to parse a date like 2018-11-28T15:24:00.000Z a exception is throwed

com.fasterxml.jackson.databind.JsonMappingException:无法构造java.time.LocalDateTime的实例:no字符串参数构造函数/工厂方法从字符串值反序列化('2018-11-28T15:24:00.000Z')

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.LocalDateTime: no String-argument constructor/factory method to deserialize from String value ('2018-11-28T15:24:00.000Z')

在我的pom.xml中,我有:

In my pom.xml i have:

  • 春季启动1.5.7
  • jackson-datatype-jdk8
  • jackson-datatype-jsr310

我的ObjectMapper Bean:

My ObjectMapper Bean:

@Bean
public ObjectMapper postConstruct() {
    return this.builder
           .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .defaultUseWrapper(false)
            .build();
}

我也尝试过:

@JsonFormat(pattern = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'", timezone ="UTC")
private LocalDateTime dateTime;

推荐答案

我也遇到过类似的问题.出现此问题的原因是,映射器无法从String对象创建LocalDateTime实例.下面将解决您的问题.

I have faced similar issues. Reason for this issue is that mapper is not able to create a LocalDateTime instance from String object. Below will solve your problem.

@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'")
private LocalDateTime dateTime;

如果您不想明确提及Serializer/Deseralizer,则必须按照JackSon指南中的任何一项进行操作,以发布DateTime Java 8增强功能.

If you don't want to explicitly mention Serializer/Deseralizer, you will have to do either of below as per JackSon guide for release of DateTime Java 8 enhancements.

ObjectMapper mapper = new ObjectMapper()
   .registerModule(new ParameterNamesModule())
   .registerModule(new Jdk8Module())
   .registerModule(new JavaTimeModule());

OR

ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();

在SpringBoot中,ObjectMapper实例为AutoWired& ;;因此,我不知道我们是否可以显式地执行任何一种解决方案.所以暂时,明确提到Serializer/Deserializer的肮脏解决方案是我最好的选择.

In SpringBoot, ObjectMapper instance is AutoWired & hence I don't know if we can explicitly do either of the solution. So for time being, dirty solution of explicitly mentioning Serializer/Deserializer is my best bet.

JackSon Java8 LocalDateTime增强自述页面如下

JackSon Java8 LocalDateTime enhancement ReadMe page is as below

https://github.com/FasterXML/jackson-modules-java8/blob/master/README.md

这篇关于杰克逊转换LocalDatetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆