Skip to content

Instantly share code, notes, and snippets.

@wolfendale
Last active October 28, 2018 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolfendale/065f9fe48dd1263cc18ac15c8e7d5ff9 to your computer and use it in GitHub Desktop.
Save wolfendale/065f9fe48dd1263cc18ac15c8e7d5ff9 to your computer and use it in GitHub Desktop.
Play JSON Reads
implicit lazy val reads: Reads[CarMotor] = {
import play.api.libs.json._
import play.api.libs.functional.syntax._
(__ \ "engineType").read[String].flatMap {
case "electric" =>
Reads.pure(Electric)
case "engine" => {
(__ \ "fuel").read[CarFuelType] and
(__ \ "engineSize").readNullable[CarEngineSize] and
(__ \ "co2").readNullable[Int]
}.apply(Engine.apply _)
case _ =>
Reads(_ => JsError("error.invalid"))
}
}
implicit lazy val reads2: Reads[CarMotor] = {
import play.api.libs.json._
import play.api.libs.functional.syntax._
val electrical: Reads[CarMotor] = __.read[String].map(_ => Electric)
val engine: Reads[CarMotor] = {
(__ \ "fuel").read[CarFuelType] and
(__ \ "engineSize").readNullable[CarEngineSize] and
(__ \ "co2").readNullable[Int]
}.apply(Engine.apply _)
electrical | engine
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment