通用 JSON 支持

Generic JSON Support

如何将 RootJsonFormat 与泛型一起使用?

我是否必须像这样复制粘贴每一种可能性:

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[_]] { ... }

无效。

首先,我假设 ID class 是这样定义的:

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")
  }
}