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)