Play Framework: How to serialize/deserialize an en

2019-02-05 19:49发布

问题:

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?

回答1:

Try changing it to

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


回答2:

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



回答3:

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
}


回答4:

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

EnumerationCombinators.scala