I am using MongoDB scala driver. I have a problem with fetching record from MongoDB. Following is my MongoDB initialization
private val client: MongoClient
You could use a JSON library.
In play-json
case class WorkOrder (
id: String,
workOrderId: String,
thingId: String,
alertId: String,
description: String,
lastViewedDate: Date,
suggestedMaintenanceDate: Date,
startDate: Date
)
object WorkOrder {
implicit lazy val fmt = Json.format[WorkOrder]
}
def documentToWorkOrder(doc: Document): WorkOrder = {
Json.parse(user.toJson().toString).validate[WorkOrder] match {
case JsSuccess(_, workOrderObj) => workOrderObj
case JsError(throwable) => throw throwable
}
}
//then in your code
MongoFactory.WorkOrdercollection.find(query).subscribe(
(user: Document) => documentToWorkOrder(user),
(error: Throwable) => println(s"Query failed: ${error.getMessage}"),
() => println("Done")
)
You need to provide a custom codec for $date
field. The following shows how it is done in play-json
but the concept is similar in other JSON libraries:
object WorkOrder {
implicit val dateRead: Reads[Date] =
(__ \ "$date").read[Long].map(date => new Date(date))
implicit val dateWrite: Writes[Date] = new Writes[Date] {
def writes(date: Date): JsValue = Json.obj("$date" -> date.getTime)
}
implicit val codec = Json.format[WorkOrder]
}