我是一名 Play 初学者,并尝试将我的 Web 应用程序从 Play 2.0.4 迁移到新的 Shiny 的 Play 2.1-RC2。由于新的 JSON 处理,我的代码无法编译。
我已阅读 Mandubians Blog , Play 2.1 Migration guide和 Play JSON library documentation (beta)但我仍然不确定迁移代码的最佳方式是什么。
F.ex。我有一个名为 File
的模型,带有隐式读取对象(Play 2.0):
object File {
implicit object FileReads extends Reads[File] {
def reads(json: JsValue) = File(
(json \ "name").as[String],
(json \ "size").as[Long]
)
}
}
我在 Controller 中这样使用它(Play 2.0):
val file = webserviceResult.json.as[models.File]
Play 2.1 迁移指南告诉我用 JsSuccess()
重构它(Play 2.1?):
object File {
implicit object FileFormat extends Format[File] {
def reads(json: JsValue) = JsSuccess(File(
(json \ "name").as[String],
(json \ "size").as[Long]
))
}
}
但是我现在如何使用这个隐式转换呢?
还是像 Twitter-example 中那样使用 implicit val
-stuff 更好?来自 Play for Scala-book ?将 JsValue 转换为其 Scala 值的最佳方法是什么?
最佳答案
Or is it better to use the implicit val-stuff like in the Twitter-example from the Play for Scala-book?
是的,对于经典的转换,这是一个很好的解决方案(简单明了)。
但是有一种更简单的方法可以使用“Json Macro Inception”实现这种转换:
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class File(name: String, size: Long)
implicit val fileFormat = Json.format[File]
val json = Json.parse("""{"name":"myfile.avi", "size":12345}""") // Your WS result
scala> json.as[File]
res2: File = File(myfile.avi,12345)
警告:您不能将格式化程序放在伴随对象中,这是当前 Json API 的限制。
我建议对所有 json 格式化程序使用一个对象,并在必要时导入它。
仅供引用,原始格式化程序应该这样写:
implicit val rawFileRead: Format[File] = (
(__ \ "name").format[String] and
(__ \ "size").format[Long]
)(File.apply _, unlift(File.unapply _)) // or (File, unlift(File.unapply))
查看这两个测试类,有很多有趣的例子:
关于json - Play 2.1-RC2 : Converting JsValue to Scala Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14291666/