- 전체
- JAVA 일반
- JAVA 수학
- JAVA 그래픽
- JAVA 자료구조
- JAVA 인공지능
- JAVA 인터넷
- Java Framework
- Java GUI (AWT,SWING,SWT,JFACE)
- SWT and RCP (web RAP/RWT)[eclipse], EMF
JAVA 자료구조 [MongoDB, Java] Deserialize MongoDB date fields to Java POJO Using Jackson
2020.11.07 15:26
[MongoDB, Java] Deserialize MongoDB date fields to Java POJO Using Jackson
[Question]
Using Spring Boot 1.4.4.RELEASE, have saved a RequestBody
to MongoDB as below:
{
"startTime" : NumberLong("1483542955570"),
"startDate" : ISODate("2017-01-04T15:15:55.570Z"),
"endTime" : NumberLong("1483542955570"),
"endDate" : ISODate("2017-01-04T15:15:55.570Z")
}
While mapping this back to a Java POJO, I am trying the below code.
public <T> T getPOJOFromMongoDocument(Document resourceDocument, Class<T> clazz) {
String serialize = JSON.serialize(resourceDocument);
return objectMapper.readValue(serialize,
clazz);
}
serialize has the date fields returned as following
"startDate" : { "$date" : "2017-01-04T15:15:55.570Z"}
Due to $date
, Jackson ObjectMapper
returns the below exception during parsing:
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"])}
Is there way to solve this without using an ODM?
[Answer]
When deserializing to Date
Jackson expects a String
like "2017-01-04T15:15:55.570Z"
. Instead, it sees the start of another object (the {
char) inside the JSON hence the exception.
Consider specifying your Pojo
class and another MongoDate
class similar to this:
class MongoDate {
@JsonProperty("$date")
Date date;
}
class Pojo {
long startTime;
long endTime;
MongoDate startDate;
MongoDate endDate;
}
Alternatively if you can't / don't want to add a MongoDate
class you can introduce a custom deserializer for Date
fields. In that case Pojo
:
class Pojo {
long startTime;
long endTime;
@JsonDeserialize(using = MongoDateConverter.class)
Date startDate;
@JsonDeserialize(using = MongoDateConverter.class)
Date endDate;
}
And the deserializer would look like this:
class MongoDateConverter extends JsonDeserializer<Date> {
private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonNode node = jp.readValueAsTree();
try {
return formatter.parse(node.get("$date").asText());
} catch (ParseException e) {
return null;
}
}
}
[출처] https://stackoverflow.com/questions/42856936/deserialize-mongodb-date-fields-to-java-pojo-using-jackson/42862417
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.