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

前端 未结 5 1172
有刺的猬
有刺的猬 2020-12-29 20:43

Given the following enumeration...

object MyEnum extends Enumeration {

  type MyEnum = Value

  val Val1 = Value(\"val1\")
  val Val2 = Value(\"val2\")
  va         


        
相关标签:
5条回答
  • 2020-12-29 21:05

    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 = Json.formatEnum(this)
    }
    
    0 讨论(0)
  • 2020-12-29 21:06

    Try changing it to

    def reads(json: JsValue) = JsSuccess(MyEnum.withName(json.as[String].value))
    
    0 讨论(0)
  • 2020-12-29 21:10

    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
    }
    
    0 讨论(0)
  • 2020-12-29 21:11

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

    EnumerationCombinators.scala

    0 讨论(0)
  • 2020-12-29 21:26

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

    0 讨论(0)
提交回复
热议问题