![](/img/trans.png)
[英]Class com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer has no default (no arg) constructor
[英]Java 8 Exception: com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer has no default (no arg) constructor
我有一個 model class 有一個字段:
@JsonDeserialize(using = InstantDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private OffsetDateTime offsetDt;
當這個 model 的請求發送到服務器時,我的 controller 拋出異常:
Caused by: java.lang.IllegalArgumentException:
Class com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer
has no default (no arg) constructor
pom.xml 有 2.8.11 版本的依賴:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
我知道這是由@JsonDeserialize 需要無參數構造函數引起的,但是有解決方法嗎?
該錯誤表明您需要一個沒有arg構造函數的類,因此可以從InstantDeserializer
擴展。 (以InstantDeserializer
中的super()
參數為例)
public class DefaultInstantDeserializer extends InstantDeserializer<OffsetDateTime> {
public DefaultInstantDeserializer() {
super(OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME,
OffsetDateTime::from,
a -> OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId),
a -> OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId),
(d, z) -> d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())),
true);
}
}
然后,您可以使用它:
@JsonDeserialize(using = DefaultInstantDeserializer.class)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.