我有這樣的模型:兩個枚舉並與這些枚舉類型的兩個領域的一個案例類:斯卡拉,噴霧JSON:通用枚舉JSON格式
// see later, why objects are implicit
implicit object Fruits extends Enumeration {
val Apple = Value("apple")
val Orange = Value("orange")
}
implicit object Vegetables extends Enumeration {
val Potato = Value("potato")
val Cucumber = Value("cucumber")
val Tomato = Value("tomato")
}
type Fruit = Fruits.Value
type Vegetable = Vegetables.Value
case class Pair(fruit: Fruit, vegetable: Vegetable)
我想分析/生成雙JSONs到/用噴霧罐。我不想爲水果和蔬菜申報單獨的JsonFormat
。所以,我希望做這樣的事情:
import spray.json._
import spray.json.DefaultJsonProtocol._
// enum is implicit here, that's why we needed implicit objects
implicit def enumFormat[A <: Enumeration](implicit enum: A): RootJsonFormat[enum.Value] =
new RootJsonFormat[enum.Value] {
def read(value: JsValue): enum.Value = value match {
case JsString(s) =>
enum.withName(s)
case x =>
deserializationError("Expected JsString, but got " + x)
}
def write(obj: enum.Value) = JsString(obj.toString)
}
// compilation error: couldn't find implicits for JF[Fruit] and JF[Vegetable]
implicit val pairFormat = jsonFormat2(Pair)
// expected value:
// spray.json.JsValue = {"fruit":"apple","vegetable":"potato"}
// but actually doesn't even compile
Pair(Fruits.Apple, Vegetables.Potato).toJson
可悲的是,enumFormat
不會爲jsonFormat2
產生隱含值。如果我寫pairFormat前水果和蔬菜的格式手動兩個隱含的聲明,然後JSON編組工作:
implicit val fruitFormat: RootJsonFormat[Fruit] = enumFormat(Fruits)
implicit val vegetableFormat: RootJsonFormat[Vegetable] = enumFormat(Vegetables)
implicit val pairFormat = jsonFormat2(Pair)
// {"fruit":"apple","vegetable":"potato"}, as expected
Pair(Fruits.Apple, Vegetables.Potato).toJson
於是,兩個問題:
如何擺脫這些
fruitFormat
和vegetableFormat
聲明?理想情況下,不要讓枚舉對象隱含,同時保持
enumFormat
函數是通用的。有沒有辦法做到這一點?也許,使用scala.reflect
包或類似的東西。
這應該是正確的答案。不明白爲什麼它被拒絕投票。 – PH88