使用Spring Boot 1.4.4.RELEASE,将RequestBody保存到MongoDB,如下所示:
{
"startTime" : NumberLong("1483542955570"),"startDate" : ISODate("2017-01-04T15:15:55.570Z"),"endTime" : NumberLong("1483542955570"),"endDate" : ISODate("2017-01-04T15:15:55.570Z")
}
在将其映射回Java POJO时,我正在尝试以下代码.
public
serialize具有如下返回的日期字段
"startDate" : { "$date" : "2017-01-04T15:15:55.570Z"}
由于$date,Jackson ObjectMapper在解析期间返回以下异常:
java.lang.RuntimeException: Error parsing mongoDoc to Pojo : errorMessage : {Can not deserialize instance of java.util.Date out of START_OBJECT token at [Source: {
"startTime": 1483542955570,"startDate": {
"$date": "2017-01-04T15:15:55.570Z"
},"endTime": 1483542955570,"endDate": {
"$date": "2017-01-04T15:15:55.570Z"
}}; line: 1,column: 381] (through reference chain: com.gofynd.engine.mongo.models.RuleWithDataVO["validity"]->com.gofynd.engine.mongo.models.ValidityVO["startDate"])}
有没有办法解决这个问题而不使用ODM?
最佳答案
反序列化到Date Jackson期望字符串如“2017-01-04T15:15:55.570Z”.相反,它会看到另一个对象的开始(JSON中的{char)因此异常.
考虑指定您的Pojo类和另一个类似于此的MongoDate类:
class MongoDate {
@JsonProperty("$date")
Date date;
}
class Pojo {
long startTime;
long endTime;
MongoDate startDate;
MongoDate endDate;
}
或者,如果您不能/不想添加MongoDate类,则可以为Date字段引入自定义反序列化器.在那种情况下Pojo:
class Pojo {
long startTime;
long endTime;
@JsonDeserialize(using = MongoDateConverter.class)
Date startDate;
@JsonDeserialize(using = MongoDateConverter.class)
Date endDate;
}
反序列化器看起来像这样:
class MongoDateConverter extends JsonDeserializer