Skip to content

Instantly share code, notes, and snippets.

@mandubian
Forked from playxamplez-admin/CODE
Last active September 30, 2021 20:03
Show Gist options
  • Save mandubian/6051831 to your computer and use it in GitHub Desktop.
Save mandubian/6051831 to your computer and use it in GitHub Desktop.
#Json #Reads/#Writes for a sealed #trait & inheriting caseclasses without type indication in Json #Play2.1
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
import play.api.libs.json._
import play.api.libs.functional.syntax._
sealed trait Shape
case class Circle(c: (Float, Float), r: Float) extends Shape
object Circle {
// reader is covariant and can be implicit in inheriting caseclasses
implicit val reader = Json.reads[Circle]
// writer is contravariant and can't be implicit in inheriting caseclasses
val writer = Json.writes[Circle]
}
case class Polygon(points: Seq[(Float, Float)]) extends Shape
object Polygon {
// reader is covariant and can be implicit in inheriting caseclasses
implicit val reader = Json.reads[Polygon]
// writer is contravariant and can't be implicit in inheriting caseclasses
val writer = Json.writes[Polygon]
}
object Shape {
// Note the map to convert into Shape because we want a Reads[Shape]
// As we don't have any type indication, we can just use try/fail strategy
implicit val shapeReads =
__.read[Rect].map(x => x:Shape) orElse __.read[Circle].map(x => x:Shape)
implicit val shapeWrites = Writes[Shape]{
case circle: Circle => Circle.writer.writes(circle)
case poly: Polygon => Polygon.writer.writes(poly)
}
}
@bmitioglov
Copy link

Thanks man!

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