Last active
December 15, 2021 23:10
-
-
Save mikesname/5237809 to your computer and use it in GitHub Desktop.
Example Play JSON Enum reading/writing
This file contains hidden or 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
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 | |
} |
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.
Thanks, worked for me.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi
line 26:
EnumReader
is not defined. I removed it and the error was gonewhen i use it like so:
the
(__ \ "status").write[Status]
works ok, but(__ \ "status").read[Status]
gives an error "Description Resource Path Location TypeNo Json formatter found for type models.Status.Status. Try to implement an implicit Format for this type"
why doesn't it work for "read"?
Thank you