Last active
October 28, 2018 16:43
-
-
Save wolfendale/065f9fe48dd1263cc18ac15c8e7d5ff9 to your computer and use it in GitHub Desktop.
Play JSON Reads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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