JSON 在 Play 框架 (Scala) 中读取硬编码值

JSON reads with hardcoded values in Play framework (Scala)

我想在 JSON 隐式读取中使用硬编码值,例如:

implicit val locationReads: Reads[Location] = (
  "I am a hardcoded value" and // something like that
  (JsPath \ "lat").read[Double] and
  (JsPath \ "long").read[Double]
)(Location.apply _)

有人知道怎么做吗?

您可以使用自定义函数代替 Location.apply:

case class Location(s: String, lat: Double, lon: Double)
object Location {
  implicit val locationReads: Reads[Location] = (
      (JsPath \ "lat").read[Double] and
      (JsPath \ "long").read[Double]
    )((lat, lon) => Location("I am a hardcoded value", lat, lon))
}

使用 Reads.pure 产生 Reads 产生一个常数值。

implicit val locationReads: Reads[Location] = (
  Reads.pure("I am a hardcoded value") and
  (JsPath \ "lat").read[Double] and
  (JsPath \ "long").read[Double]
)(Location.apply _)