2014-05-22 14 views
16

Dato il seguente enumerazione ...quadro Giocare: Come serializzare/deserializzare un'enumerazione da/JSON

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) 
    } 
} 

... Ho bisogno di serializzare/deserializzare a/da JSON. myEnumFormat non compila e ho sempre ottenere il seguente messaggio di errore:

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) 

Mi sto perdendo qualcosa?

risposta

13

Provare a cambiare a

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

ho messo insieme più generico e riutilizzabile EnumerationReads, EnumerationWrites e classi EnumerationFormat e li ho postato sulla mia pagina GitHub:

EnumerationCombinators.scala

17

implicit val genderReads = Reads.enumNameReads(Gender) sta funzionando bene per me. Gioca Scala 2.4.2

+0

Questa è una buona risposta - non sapevo esistessero questi – MrProper

0

Espansione sulla risposta di @ surenyonjan, le seguenti opere ben con il gioco 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 
} 
Problemi correlati