Search code examples
jsonscalaplayframeworkjava-8play-json

Scala / Play 2.4 JSON Format issue


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?


Solution

  • Instead of:

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

    Try:

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