Created
May 28, 2014 18:53
-
-
Save retroryan/603d95313c3e5f2ec5c3 to your computer and use it in GitHub Desktop.
Play Json Reading a Recursive Class - Alternative Solution
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
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