Skip to content

Instantly share code, notes, and snippets.

@nbenns
Created June 19, 2017 15:03
Show Gist options
  • Save nbenns/ce53ed2734777b6900c2d9840d9c72ba to your computer and use it in GitHub Desktop.
Save nbenns/ce53ed2734777b6900c2d9840d9c72ba to your computer and use it in GitHub Desktop.
better scala enum with play reads/writes
import play.api.libs.json._
sealed trait Color
object Color {
type Red = Red.type
type Green = Green.type
type Blue = Blue.type
case object Red extends Color
case object Green extends Color
case object Blue extends Color
implicit val colorReads: Reads[Color] = new Reads[Color] {
override def reads(json: JsValue): JsResult[Color] = json match {
case JsString("Red") => JsSuccess(Red)
case JsString("Green") => JsSuccess(Green)
case JsString("Blue") => JsSuccess(Blue)
case _ => JsError("Bad Color")
}
}
implicit val colorWrites: Writes[Color] = new Writes[Color] {
override def writes(o: Color): JsValue = o match {
case Red => JsString("Red")
case Green => JsString("Green")
case Blue => JsString("Blue")
}
}
}
case class Meh(id: Int, color: Color)
implicit val MehReads = Json.reads[Meh]
val obj = Json.obj(
"id" -> 1,
"color" -> "Green"
)
val meh: JsResult[Meh] = Json.fromJson[Meh](obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment