Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework: How to serialize/deserialize an enumeration to/from JSON

Given the following enumeration...

object MyEnum extends Enumeration {

  type MyEnum = Value

  val Val1 = Value("val1")
  val Val2 = Value("val2")
  val ValN = Value("valN")

  implicit val myEnumFormat = new Format[MyEnum] {
    def reads(json: JsValue) = MyEnum.withName(json.as[String].value) // doesn't compile
    def writes(myEnum: MyEnum) = JsString(myEnum.toString)
  }
}

... I need to serialize/deserialize it to/from JSON. myEnumFormat does not compile and I always get the following error message:

type mismatch;
[error]  found   : models.MyEnum.Value
[error]  required: play.api.libs.json.JsResult[models.MyEnumValue]
[error]  Note: implicit value myEnumFormat is not applicable here because it comes after the application point and it lacks an explicit result type
[error]     def reads(json: JsValue) = MyEnum.withName(json.as[JsString].value)

Am I missing something?

like image 366
j3d Avatar asked May 22 '14 20:05

j3d


4 Answers

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

like image 165
surenyonjan Avatar answered Oct 17 '22 22:10

surenyonjan


Try changing it to

def reads(json: JsValue) = JsSuccess(MyEnum.withName(json.as[String].value))
like image 34
Artur Nowak Avatar answered Oct 17 '22 22:10

Artur Nowak


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
}
like image 15
Narayanan Balakrishnan Avatar answered Oct 17 '22 21:10

Narayanan Balakrishnan


Play 2.7

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: Format[MyEnum] = Json.formatEnum(this)
}
like image 11
Andrii Abramov Avatar answered Oct 17 '22 21:10

Andrii Abramov