joda.time.DateTime反序列化错误 [英] joda.time.DateTime deserialization error

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

问题描述

我尝试将DateTime反序列化为attibute:

I tried to deserialize a class with a DateTime as attibute:

import org.joda.time.DateTime;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer;
import com.fasterxml.jackson.datatype.joda.ser.DateTimeSerializer;

class MyClass {

    private DateTime alertTimestamp;

    private String name;

    @JsonSerialize(using = DateTimeSerializer.class)
    public DateTime getAlertTimestamp() {
        return alertTimestamp;
    }

    @JsonDeserialize(using = DateTimeDeserializer.class)
    public void setAlertTimestamp(DateTime now) {
        this.alertTimestamp = now;
    }

    //...
}



<但是,当我尝试反序列化时,我有这个例外:

But when I try tro deserialize, I have this exception:

com.fasterxml.jackson.datatype.joda.deser.DateTimeDeserializer has no default (no arg) constructor

我用它来反序列化:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonData, MyClass.class);

我的jsonData示例:

And an example of my jsonData:

{    
    "name":"test",
    "alertTimestamp":       {"year":2014,"era":1,"dayOfMonth":24,"dayOfWeek":1,"dayOfYear":83,"weekOfWeekyear":13,"weekyear":2014,"monthOfYear":3,"yearOfEra":2014,"yearOfCentury":14,"centuryOfEra":20,"millisOfSecond":232,"millisOfDay":45143232,"secondOfMinute":23,"secondOfDay":45143,"minuteOfHour":32,"minuteOfDay":752,"hourOfDay":12,"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"America/Los_Angeles"},"fixed":false,"id":"America/Los_Angeles"},"millis":1395689543232,"chronology":{"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"America/Los_Angeles"},"fixed":false,"id":"America/Los_Angeles"}},"afterNow":false,"beforeNow":false,"equalNow":true}
}


推荐答案

@JsonDeserialize 期望带有无参数的 JsonDeserializer 构造函数。最新版本的 DateTimeDeserializer 没有这样的构造函数。

@JsonDeserialize expects a JsonDeserializer with a no-arg constructor. The most recent version of DateTimeDeserializer does not have such a constructor.

如果你已经修改了格式,即。 alertTimestamp 应该只是一个时间戳,然后您只需使用 ObjectMapper <注册 JodaModule / code>。它将在 DateTime 字段内部使用 DateTimeDeserializer 。你可以摆脱 @JsonDeserialize 注释。

If you've fixed the format, ie. alertTimestamp should just be a timestamp, then you could simply register the JodaModule with the ObjectMapper. It will use DateTimeDeserializer internally for DateTime fields. You can get rid of the @JsonDeserialize annotations.

mapper.registerModule(new JodaModule());

你需要添加 jackson-datatype-joda library。

You'll need to add the jackson-datatype-joda library.

这篇关于joda.time.DateTime反序列化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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