我有这样的模型:两个枚举和一个案例类,其中包含这些枚举类型的两个字段:
// 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)
我希望使用spray-json来解析/生成与Pairs相关的JSON。我不想为水果和蔬菜分别声明单独的
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
包或类似的东西。