【发布时间】:2018-03-18 15:22:36
【问题描述】:
我有这样的模型:两个枚举和一个案例类,其中包含这些枚举类型的两个字段:
// 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。我不想为水果和蔬菜单独声明JsonFormats。所以,我想做这样的事情:
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 marshalling 就可以了:
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包或类似的东西。
【问题讨论】:
标签: json scala enums spray-json