简体   繁体   中英

JSON reads with hardcoded values in Play framework (Scala)

I'd like to use hardcoded values in JSON implicit reads, something like:

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

Does anyone know how to do this?

Use Reads.pure to produce Reads that yield a constant value.

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

You can do that by using a custom function istead of 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))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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