ZonedDateTime的杰克逊反序列化问题

编程入门 行业动态 更新时间:2024-10-25 13:23:01
本文介绍了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的杰克逊反序列化问题

本文发布于:2023-08-04 05:56:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293560.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:杰克逊   序列化   ZonedDateTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!