如何在 Scala 和 play 框架中从 Format 创建 OFormat [英] How to create OFormat from Format in scala and play framework
问题描述
如何以与使用 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
如果有人能解释为什么或如何在没有 RuntimeException
的情况下使用隐式",我会很高兴听到.
If anyone can explain why or how to use "implicit" without that RuntimeException
I would be happy to hear.
我正在运行 Java 8,玩 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!