Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Play Json Reading a Recursive Class - Alternative Solution
trait Animal
case class Bird(name: String, wings: Boolean) extends Animal
case class Horse(name: String, height: Double) extends Animal
object Animal {
implicit val birdReads: Reads[Bird] = (
(JsPath \ "name").read[String] and
(JsPath \ "wing").read[Boolean]
)(Bird.apply _)
implicit val horseReads: Reads[Horse] = (
(JsPath \ "name").read[String] and
(JsPath \ "height").read[Double]
)(Horse.apply _)
def fromJson(json: JsValue): JsResult[Animal] = {
(json \ "wings").asOpt[Boolean] match {
case Some(true) => json.validate[Bird](birdReads)
case _ => json.validate[Horse](horseReads)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment