2017-08-17 8 views
1

私はそのような私のプログラムでJSON形式の変換に列挙型の暗黙的なヴァルの多くを持っている:Scalaの一般的な暗黙のヴァル

implicit val format = new Format[AuthRoleIndividual] { 
    def reads(json: JsValue) = JsSuccess(AuthRoleIndividual.withName(json.as[String])) 
    def writes(myEnum: AuthRoleIndividual) = JsString(myEnum.toString) 
    } 

注:AuthRoleIndividualEnumerationを拡張します。私のアプローチは次のようなものを書くことでした:

implicit val format[T <: Enumeration] = new Format[T] { 
    def reads(json: JsValue) = JsSuccess(T.withName(json.as[String])) 
    def writes(myEnum: T) = JsString(myEnum.toString) 
    } 

しかし、それはできません。何か案は?あなたがValueタイプにimplicitをバインドする必要がありますので

+1

ところでPlay JSONは既に['Writes']を提供しています(https://www.playframework.com/documentation/2.6.0/api/scala/index.html#play.api.libs.json.Writes$ @enumNameWrites [E%3C:Enumeration]:play.api.libs.json.Writes [E#Value])および['Reads'](https://www.playframework.com/documentation/2.6.0/api/列挙のためにscala/index.html#[email protected] [E%3C:列挙型](列挙型:E):play.api.libs.json.Reads [E#値]) – cchantep

答えて

1

まず、あなたがEnumeration値については、Enumeration値の型を誤解している、のタイプは、ValueタイプではないEnumerationです。たとえば、次のようにValueタイプはobjectState.value)にバインドされているので

object State extends Enumeration { 
    val A = Value("A") 
    val B = Value("B") 
    } 

    implicit def foo(v: State.Value): String = v.toString + "-Bar" 

    val t: String = State.A 

第二に、上記のコードのように、あなたはジェネリック暗黙にすべてのEnumerationためを作成することはできません。

+0

ありがとう明確化のために非常に! – perotom

関連する問題