简体   繁体   English

Scala Play在构造上读取Json和LocalDateTime

[英]Scala Play Read Json and LocalDateTime on construct

I have a simple case class Location (It's pretty much the ScalaJsonCombinators tutorial) 我有一个简单的案例类Location(几乎是ScalaJsonCombinators教程)

// 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. 不幸的是,我不能真正弄清楚如何使用Play Json来传递LocalDateTime.now()而不发送附加字段,或者实际上通常如何传递LocalDateTime。

The Request Body 请求主体

{ 
     "latitude": ...
     "longitude": ...
}

Rather than passing Location.unapply / Location.apply to the FunctionalBuilder you can pass your own functions: 您可以传递自己的函数,而不是将Location.unapply / Location.apply传递给FunctionalBuilder

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()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM