ZonedDateTime的杰克逊反序列化问题 [英] Jackson deserialization issue for ZonedDateTime

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

问题描述

我在我正在使用的服务的反序列化过程中使用的类中有以下字段。

I've the following field in a class I use during deserialization of a service that I'm consuming.

private ZonedDateTime transactionDateTime;

我正在使用的服务可能会使用以下模式返回Date或DateTime: yyyy-MM-dd'T'HH:mm:ss.SSSZ

The service I'm consuming may return a Date or DateTime using the pattern: yyyy-MM-dd'T'HH:mm:ss.SSSZ

让我举两个例子说明服务返回的内容:

Let me give 2 examples of what the service returns:


  • 2015-11-18T18:05:38.000 + 0200

  • 2015-11-18T00:00 :00.000 + 0200

虽然第一个效果很好,后者会在反序列化过程中抛出以下异常:

While first one works well, the latter causes the following exception to be thrown during deserialization:


java.time.format.DateTimeParseException:文本
'2015-11-18T00:00:00.000 + 0200'无法在索引23处解析

java.time.format.DateTimeParseException: Text '2015-11-18T00:00:00.000+0200' could not be parsed at index 23

我正在使用;


  • Spring Boot 1.3.1

  • Jackson 2.6.4(包含JSR310模块)

这需要一个自定义反序列化类吗?

Does this require a custom deserialization class?

推荐答案

在代码的前面我使用的字段是 @JsonFormat 注释但删除编辑,因为我认为它仅用于序列化,就像JavaDocs建议的那样。

Earlier in the code I was using the field with @JsonFormat annotation but removed that as I thought it was meant for serialization only like the JavaDocs suggest.

原来我需要添加那个注释。真正的问题是第三方服务响应确实是错误的(它缺少XML中的包装元素)导致反序列化失败。错误是:

Turned out that I needed add back that annotation. And the real issue was that the 3rd party service response was indeed wrong (it was missing a wrapper element in the XML) which caused the deserialisation to fail. The error was:


com.fasterxml.jackson.databind.JsonMappingException:
不能实例化类型[simple type, class
com.foo.bar.adapter.john.model.account.UserAccount]
from String value('2015-11-18T00:00:00.000 + 0200');没有单字符串
构造函数/工厂方法

com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.foo.bar.adapter.john.model.account.UserAccount] from String value ('2015-11-18T00:00:00.000+0200'); no single-String constructor/factory method

该字段的编写如下:

@JsonFormat(pattern = Constants.DATETIME_FORMAT)
@JacksonXmlProperty(localName = "transactionDate")
private ZonedDateTime transactionDateTime;

此外我还要添加 @JsonRootName(交易)到该字段的类,因为该对象被包装到一个集合中。

Also I had to add @JsonRootName("transaction") to the class of this field because the object is wrapped into a collection.

这篇关于ZonedDateTime的杰克逊反序列化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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