Skip to content

Instantly share code, notes, and snippets.

@mikesname
Last active December 15, 2021 23:10
Show Gist options
  • Select an option

  • Save mikesname/5237809 to your computer and use it in GitHub Desktop.

Select an option

Save mikesname/5237809 to your computer and use it in GitHub Desktop.
Example Play JSON Enum reading/writing
package enumtest
import play.api.libs.json._
object EnumUtils {
def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = new Reads[E#Value] {
def reads(json: JsValue): JsResult[E#Value] = json match {
case JsString(s) => {
try {
JsSuccess(enum.withName(s))
} catch {
case _: NoSuchElementException => JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
}
}
case _ => JsError("String value expected")
}
}
implicit def enumWrites[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
def writes(v: E#Value): JsValue = JsString(v.toString)
}
implicit def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
Format(EnumReader.enumReads(enum), EnumWriter.enumWrites)
}
}
// Now let's test it
object EnumTest {
object EnumA extends Enumeration {
type EnumA = Value
val VAL1, VAL2, VAL3 = Value
}
implicit val enumAFormat = EnumUtils.enumFormat(EnumA)
val myEnumJson: JsValue = Json.toJson(EnumA.VAL1)
val myValue: EnumA.Value = myEnumJson.asOpt[EnumA.Value].getOrElse(sys.error("Oh noes! Invalid value!"))
def ok = EnumA.VAL1 == myValue
}
@fdz5
Copy link
Copy Markdown

fdz5 commented Oct 8, 2013

In line 26 just change the EnumReader to EnumUtils. After that you should be able to write something like this:

implicit val enumTypeFormat = EnumUtils.enumFormat(EnumClass)

At least for me it works.

@vega113
Copy link
Copy Markdown

vega113 commented Jan 22, 2015

Thanks, worked for me.

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