How to create OFormat from Format in scala and pla

2020-03-30 02:01发布

问题:

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

回答1:

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)