Jackson jsr310中缺少ZonedDateTimeDeserializer

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

我正在使用这样解析ZonedDateTime

 @JsonSerialize(using = ZonedDateTimeSerializer.class)
 private ZonedDateTime expirationDateTime;

我需要能够正确地反序列化这个日期。但是,jackson没有为此提供解串器:

com.fasterxml.jackson.datatype.jsr310.deser

有没有理由错过它?什么是最常见的解决方法?

更新:这是我的方案:

我像这样创建ZonedDateTime

ZonedDateTime.of(2017, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC)

然后我序列化包含日期的对象,如下所示:

public static String toJSON(Object o) {
    ObjectMapper objectMapper = new ObjectMapper();
    StringWriter sWriter = new StringWriter();
    try {
        JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(sWriter);
        objectMapper.writeValue(jsonGenerator, o);
        return sWriter.toString();
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

当我尝试将其发送到Spring MVC Controller时:

    mockMvc.perform(post("/endpoint/")
            .content(toJSON(myObject))
            .contentType(APPLICATION_JSON))
            .andExpect(status().isOk());

进入控制器内部的日期对象是不同的。

之前:2017-01-01T01:01:01.000000001Z

之后:2017-01-01T01:01:01.000000001Z[UTC]

java jaxb jackson date-parsing zoneddatetime
2个回答
3
投票

2个值2017-01-01T01:01:01.000000001Z2017-01-01T01:01:01.000000001Z[UTC]实际上代表相同的瞬间,因此它们是等效的并且可以毫无问题地使用(至少应该没有问题,因为它们代表相同的瞬间)。

唯一的细节是杰克逊出于某种原因,在反序列化时将ZoneId值设置为“UTC”,这在这种情况下是多余的(Z已经告诉偏移是“UTC”)。但它不应该影响日期值本身。


摆脱这个[UTC]部分的一个非常简单的方法是将此对象转换为OffsetDateTime(因此它保持Z偏移并且不使用[UTC]区域)然后再次返回ZonedDateTime

ZonedDateTime z = // object with 2017-01-01T01:01:01.000000001Z[UTC] value
z = z.toOffsetDateTime().toZonedDateTime();
System.out.println(z); // 2017-01-01T01:01:01.000000001Z

在那之后,z变量的值将是2017-01-01T01:01:01.000000001Z(没有[UTC]部分)。

但当然这并不理想,因为你必须手动完成所有日期。更好的方法是编写一个自定义反序列化器(通过扩展com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer),它在UTC时不设置时区:

public class CustomZonedDateTimeDeserializer extends InstantDeserializer<ZonedDateTime> {
    public CustomZonedDateTimeDeserializer() {
        // most parameters are the same used by InstantDeserializer
        super(ZonedDateTime.class,
              DateTimeFormatter.ISO_ZONED_DATE_TIME,
              ZonedDateTime::from,
              // when zone id is "UTC", use the ZoneOffset.UTC constant instead of the zoneId object
              a -> ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId.getId().equals("UTC") ? ZoneOffset.UTC : a.zoneId),
              // when zone id is "UTC", use the ZoneOffset.UTC constant instead of the zoneId object
              a -> ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId.getId().equals("UTC") ? ZoneOffset.UTC : a.zoneId),
              // the same is equals to InstantDeserializer
              ZonedDateTime::withZoneSameInstant, false);
    }
}

然后你必须注册这个解串器。如果你使用ObjectMapper,你需要将它添加到JavaTimeModule

ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
// add my custom deserializer (this will affect all ZonedDateTime deserialization)
module.addDeserializer(ZonedDateTime.class, new CustomZonedDateTimeDeserializer());
objectMapper.registerModule(module);

如果你在Spring中配置它,配置将是这样的(未经测试):

<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" id="pnxObjectMapper">
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry>
                <key>
                    <value>java.time.ZonedDateTime</value>
                </key>
                <bean class="your.app.CustomZonedDateTimeDeserializer">
                </bean>
            </entry>
        </map>
    </property>
</bean>

0
投票

我用这个:

        JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer(DateTimeFormatter.ISO_DATE_TIME));
    javaTimeModule.addDeserializer(ZonedDateTime.class, InstantDeserializer.ZONED_DATE_TIME);
© www.soinside.com 2019 - 2024. All rights reserved.