我有以下类(简化了一点),它将使用ID字段扩展表示数据库级别的某些对象的JSON格式:
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格式有效?
答案 0 :(得分:2)
而不是:
(__ \ "id").format[Option[Long]]
尝试:
(__ \ "id").formatNullable[Long]