java – joda.time.DateTime反序列化错误

前端之家收集整理的这篇文章主要介绍了java – joda.time.DateTime反序列化错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图用DateTime反序列化一个类作为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;
    }

    //...
}

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

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

我用它来反序列化:

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

以及我的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"},"millis":1395689543232,"chronology":{"zone":{"uncachedZone":{"cachable":true,"id":"America/Los_Angeles"}},"afterNow":false,"beforeNow":false,"equalNow":true}
}

解决方法

@JsonDeserialize需要一个带有无参数构造函数的JsonDeserializer.最新版本的DateTimeDeserializer没有这样的构造函数.

如果你已经修改了格式,即. alertTimestamp应该只是一个时间戳,然后你可以简单地用ObjectMapper注册JodaModule.它将在DateTime字段内部使用DateTimeDeserializer.您可以删除@JsonDeserialize注释.

mapper.registerModule(new JodaModule());

您需要添加jackson-datatype-joda库.

猜你在找的Java相关文章