Reputation: 1098
I have a simple case class Location (It's pretty much the ScalaJsonCombinators tutorial)
// controller
implicit val locationWrites: Writes[Location] =
(
(JsPath \ "latitude").write[Double] and
(JsPath \ "longitude").write[Double]
) (unlift(Location.unapply))
implicit val locationReads: Reads[Location] =
(
(JsPath \ "latitude").read[Double] and
(JsPath \ "longitude").read[Double]
) (Location.apply _)
// model
case class Location(latitude: Double, longitude: Double)
object Location {
implicit val formatter = Json.format[Location]
}
I want to set the current time on the construction, so that my Location would look like:
case class Location(latitude: Double, longitude: Double, date: LocalDateTime)
Unfortunately I can't really figure out how to use Play Json to pass LocalDateTime.now() without sending an additional field or actually how to pass the LocalDateTime in general.
The Request Body
{
"latitude": ...
"longitude": ...
}
Upvotes: 0
Views: 311
Reputation: 466
Rather than passing Location.unapply
/ Location.apply
to the FunctionalBuilder
you can pass your own functions:
case class Location(latitude: Double, longitude: Double, date: LocalDateTime)
implicit val locationWrites: Writes[Location] =
(
(JsPath \ "latitude").write[Double] and
(JsPath \ "longitude").write[Double]
) ((l: Location) => (l.latitude, l.longitude))
implicit val locationReads: Reads[Location] =
(
(JsPath \ "latitude").read[Double] and
(JsPath \ "longitude").read[Double]
) ((lat: Double, lon: Double) => Location(lat, lon, LocalDateTime.now()))
Upvotes: 2