Given the following enumeration...
object MyEnum extends Enumeration {
type MyEnum = Value
val Val1 = Value(\"val1\")
val Val2 = Value(\"val2\")
va
Since play-json 2.7 there is Json.formatEnum method. Added in scope of #140
Example:
object MyEnum extends Enumeration {
type MyEnum = Value
val Val1 = Value("val1")
val Val2 = Value("val2")
val ValN = Value("valN")
implicit val format = Json.formatEnum(this)
}
Try changing it to
def reads(json: JsValue) = JsSuccess(MyEnum.withName(json.as[String].value))
Expanding on @surenyonjan's response, the following works nicely with Play Json 2.6:
object MyEnum extends Enumeration {
type MyEnum = Value
val e1, e2 = Value
implicit val myEnumReads = Reads.enumNameReads(MyEnum)
implicit val myEnumWrites = Writes.enumNameWrites
}
I have put together more generic and re-usable EnumerationReads, EnumerationWrites and EnumerationFormat classes and have posted them on my github page:
EnumerationCombinators.scala
implicit val genderReads = Reads.enumNameReads(Gender)
is working fine for me. Play Scala 2.4.2