[ACCEPTED]-Play Framework: How to serialize/deserialize an enumeration to/from JSON-playframework

Accepted answer
Score: 34

implicit val genderReads = Reads.enumNameReads(Gender) is working fine for me. Play Scala 2.4.2

0

Score: 17

Try changing it to

def reads(json: JsValue) = JsSuccess(MyEnum.withName(json.as[String].value))

0

Score: 15

Expanding on @surenyonjan's response, the 1 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
}
Score: 11

Play 2.7

Since play-json 2.7 there is Json.formatEnum method. Added 1 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: Format[MyEnum] = Json.formatEnum(this)
}
Score: 3

I have put together more generic and re-usable 3 EnumerationReads, EnumerationWrites and 2 EnumerationFormat classes and have posted 1 them on my github page:

EnumerationCombinators.scala

More Related questions