【问题标题】:Scala / Play 2.4 JSON Format issueScala / Play 2.4 JSON 格式问题
【发布时间】:2015-11-18 13:40:24
【问题描述】:

我有以下类(在此处进行了一些简化),它将扩展 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 格式正常工作?

【问题讨论】:

    标签: json scala playframework java-8 play-json


    【解决方案1】:

    代替:

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

    试试:

    (__ \ "id").formatNullable[Long]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 2019-04-04
      • 2015-04-30
      • 1970-01-01
      • 2012-12-01
      相关资源
      最近更新 更多