1

我有以下类(那里简化了一点),它将扩展 JSON 格式的某些对象,这些对象代表具有 ID 字段的数据库级别:

import play.api.libs.json._
import play.api.libs.functional.syntax._

class EntityFormat[T <: Entity](entityFormatter: Format[T]) extends Format[T] {
  val extendedFormat: Format[T] = (
      __.format[T](entityFormatter) ~
     (__ \ "id").format[Option[Long]]
  )(tupleToEntity, entityToTuple)

  private def tupleToEntity(e: T, id: Option[Long]) = {
    e.id = id
    e
  }

  private def entityToTuple(e: T) = (e, e.id)

  def writes(o: T): JsValue = extendedFormat.writes(o)

  def reads(json: JsValue): JsResult[T] = extendedFormat.reads(json)
}

abstract class Entity {
  var id: Option[Long] = None
}

使用 Play 2.3,我可以编写

implicit val userFormat: Format[User] = new EntityFormat(Json.format[User])

然后它将与生成的 JSON 中的 ID 字段一起使用。但是,在 Play 2.4 中,我遇到了以下编译时问题:

No Json formatter found for type Option[Long]. Try to implement an implicit Format for this type. (__ \ "id").format[Option[Long]]
missing arguments for method tupleToEntity in class DomainEntityFormat; follow this method with `_' if you want to treat it as a partially applied function )(tupleToEntity, entityToTuple)
                                                                                                                                                              ^
missing arguments for method tupleToEntity in class DomainEntityFormat; follow this method with `_' if you want to treat it as a partially applied function )(tupleToEntity, entityToTuple)
                                                                                                                                                                             ^

您应该如何使用 Play 2.4 进行扩展以使这种 JSON 格式正常工作?

4

1 回答 1

2

代替:

(__ \ "id").format[Option[Long]]

尝试:

(__ \ "id").formatNullable[Long]
于 2015-11-18T18:50:58.250 回答