问题描述
如何用与我用Json.Format[T]
创建它的简单方法一样为案例类创建OFormat [T]?
How to create OFormat[T] for case class in the same simple way I've created it with Json.Format[T]
?
推荐答案
这是我发现的(非常简单的)解决方案:创建一个辅助对象:
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
}
}
并像这样使用它:
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])
我有java.lang.RuntimeException
如果没有人可以解释为什么或如何使用隐式",则我会很高兴.
If anyone can explain why or how to use "implicit" without that RuntimeException
I would be happy to hear.
我正在用Java 8,Play 2.4.0和Scala 2.11.7运行(显然FileToSaveData
是我要序列化的案例类)
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)
这篇关于如何在Scala和Play框架中从Format创建OFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!