通用JSON支持

时间:2016-09-21 16:41:53

标签: scala generics spray akka-http spray-json

如何将RootJsonFormat与Generics一起使用?

我是否必须复制粘贴这样的所有可能性:

trait IDJsonSupport
  extends SprayJsonSupport
    with DefaultJsonProtocol{

  implicit object AddressIDFormat extends RootJsonFormat[ID[Address]] {
    override def write(obj: ID[Address]): JsValue = JsNumber(obj.value)
    override def read(json: JsValue): ID[Address] = json match {
      case JsNumber(id) => new ID[Address](id.toLongExact)
      case _ => deserializationError("Address ID expected")
    }
  }

  implicit object CompanyIDFormat extends RootJsonFormat[ID[Company]] {
    override def write(obj: ID[Company]): JsValue = JsNumber(obj.value)
    override def read(json: JsValue): ID[Company] = json match {
      case JsNumber(id) => new ID[Company](id.toLongExact)
      case _ => deserializationError("Company ID expected")
    }
  }

  implicit object NoteIDFormat extends RootJsonFormat[ID[Note]] {
    override def write(obj: ID[Note]): JsValue = JsNumber(obj.value)
    override def read(json: JsValue): ID[Note] = json match {
      case JsNumber(id) => new ID[Note](id.toLongExact)
      case _ => deserializationError("Note ID expected")
    }
  }

  ...

此:

implicit object AnyIDFormat extends RootJsonFormat[ID[_]] { ... }

不起作用。

1 个答案:

答案 0 :(得分:0)

首先,我假设ID类定义如下:

case class ID[T](value: Long)

如果是这样,您可以定义通用格式implicit def,Scala编译器将自动创建特定格式。

implicit def genericIDFormat[T]: RootJsonFormat[ID[T]] = new RootJsonFormat[ID[T]] {
  override def write(obj: ID[T]): JsValue = JsNumber(obj.value)
  override def read(json: JsValue): ID[T] = json match {
    case JsNumber(id) => ID(id.toLongExact)
    case _ => deserializationError("ID expected")
  }
}