Skip to content

Instantly share code, notes, and snippets.

@retroryan
Created May 28, 2014 18:53
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 retroryan/603d95313c3e5f2ec5c3 to your computer and use it in GitHub Desktop.
Save retroryan/603d95313c3e5f2ec5c3 to your computer and use it in GitHub Desktop.
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