Scala / Play 2.4 JSON Format issue

末鹿安然 提交于 2019-12-11 10:55:46

问题


I have following class (simplified a bit there) that would extend the JSON-format for certain objects that represent the Database-level with the ID-field:

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
}

With Play 2.3, I could then write

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

Which would then work with with the ID-field being in the generated JSON. However, with Play 2.4 I'm getting following compile-time issues:

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)
                                                                                                                                                                             ^

How should you do the extending with Play 2.4 to make that kind of JSON Format work?


回答1:


Instead of:

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

Try:

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


来源:https://stackoverflow.com/questions/33781605/scala-play-2-4-json-format-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!