5

I'm using mongo-scala combination in one of my new projects and it requires deserializing a mongo document with date field

mongo document example

{
    "_id" : ObjectId("56603577616e082f559da3d9"),
    "type" : "rule",
    "startTime" : ISODate("2004-09-04T17:05:22.000Z"),
    "finishTime" : ISODate("2005-09-04T18:06:22.000Z"),
    "status" : "success"
}

I'm using mongo-scala-driver to query the collections and document.toJson() is givin me json string as

{ 
"_id" : { "$oid" : "56603577616e082f559da3d9" }, 
"type" : "rule", 
"startTime" : { "$date" : 1094317522000 },
"finishTime" : { "$date" : 1125857182000 }, 
"status" : "success" 
}

I need to deserialize this json string to my scala case class

case class Joblog (
                     _id : ObjectId,
                     type : String,
                     startTime: java.util.Date,
                     finishTime: java.util.Date,
                     status:String
)

I used json4s-mongo to extract scala objects after parsing json

parse(jobdoc.toJson()).extract[JobLog]

error returned was

Do not know how to convert JObject(List(($date,JInt(1094317522000)))) into class java.util.Date

looking further I noticed that json4s-mongo doesn't handle $date nameField and instead handles $dt namefield .

enter image description here

The Above approach is working perfectly for ObjectId and String datatypes but gives error only for DateField .

What is the correct way to deserialize DateField?

Rohit
  • 1,878
  • 19
  • 26

0 Answers0