Skip to content

Instantly share code, notes, and snippets.

@mandubian
Created April 16, 2013 15:18
Show Gist options
  • Save mandubian/5396793 to your computer and use it in GitHub Desktop.
Save mandubian/5396793 to your computer and use it in GitHub Desktop.
An recursive class Reads using the great lazyRead stuff... (Myself, I'm even astonished that it works :D)
sealed abstract trait Tree
case class Leaf(a: String) extends Tree
case class Node(l: Tree, r: Tree) extends Tree
implicit val treeR: Reads[Tree] =
__.read[Leaf].map(x => x:Tree) orElse
(
(__ \ "l").lazyRead(treeR) and (__ \ "r").lazyRead(treeR)
)(Node.apply _).map(x => x:Tree)
scala> treeR.reads(Json.obj("a" -> "toto"))
res10: play.api.libs.json.JsResult[Tree] = JsSuccess(Leaf(toto),/a)
scala> treeR.reads(Json.obj("l" -> Json.obj("a" -> "toto"), "r" -> Json.obj("a" -> "tata")))
res11: play.api.libs.json.JsResult[Tree] = JsSuccess(Node(Leaf(toto),Leaf(tata)),)
@abelbryo
Copy link

implicit val treeW: Writes[Tree] = new Writes[Tree] {
   def writes(ins: Tree): JsValue = ins match {
     case l: Leaf    => Json.toJson(l)(Json.writes[Leaf])
     case Node(l, r) => Json.obj("l" -> writes(l), "r" -> writes(r))
   }
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment