2

How to create OFormat[T] for case class in the same simple way I've created it with Json.Format[T]?

ozma
  • 1,633
  • 1
  • 20
  • 28
  • 1
    In Play 2.5.x, `Json.format[A]` _does_ return an `OFormat[A]`. Why it took so many versions for that to be the case, I don't know, since the macro was only ever meant for objects. – Michael Zajac May 20 '16 at 12:46

1 Answers1

3

This the (very) simple solution that I've found: create an helper object:

import play.api.libs.json.{Format, OFormat, JsObject, JsValue, JsResult}

object JsonUtil {

  def oFormat[T](format:Format[T]) : OFormat[T] = {
    val oFormat: OFormat[T] = new OFormat[T](){
      override def writes(o: T): JsObject = format.writes(o).as[JsObject]
      override def reads(json: JsValue): JsResult[T] = format.reads(json)
    }
    oFormat
  }
}

and use it like this:

import play.modules.reactivemongo.json._
implicit val formatFileToSave : Format[FileToSaveData]  = Json.format[FileToSaveData]
implicit val oFormatFileToSave: OFormat[FileToSaveData] = JsonUtil.oFormat(formatFileToSave)

I would like the "format" to be passed explicitly but when I've tried to run with the following

def oFormat[T]()(implicit format:Format[T]) I've got java.lang.RuntimeException

If anyone can explain why or how to use "implicit" without that RuntimeException I would be happy to hear.

I am runnng with Java 8, play 2.4.0 and scala 2.11.7 (obviously FileToSaveData is the case class I wanted to serialize)

ozma
  • 1,633
  • 1
  • 20
  • 28