【问题标题】:Playframework 2.2.X scala - How can I use implicit variable in json's WritesPlayframework 2.2.X scala - 我如何在 json 的写入中使用隐式变量
【发布时间】:2014-05-19 16:50:22
【问题描述】:

我使用 Play 2.2 json 写入助手:http://www.playframework.com/documentation/2.2.x/ScalaJson

我想写一个 json 版本的 File case 类。这是我的作者:

implicit val fileWrites = new Writes[File] {
def writes(file: File) = Json.obj(
  "name" -> file.name,
  "description" -> file.description,
  "contentType" -> file.contentType,
  "lastModify" -> file.lastModify,
  "size" -> file.size,
  "link" -> routes.Document.downloadFromPermalink(file.uuid).absoluteURL(false)
  )
}

但是,这个routes.Document.downloadFromPermalink(file.uuid).absoluteURL(false) 需要一个implicit request: RequestHeader。如果我将 fileWrites 定义放在具有隐式请求范围的操作中,它就可以工作。

但我想将 fileWrites 定义为可在操作之间重用。我该如何编写它以便 fileWrites 将隐式请求作为参数?

这个定义也有同样的问题:

implicit val fileWrites: Writes[File] = (
  (JsPath \ "name").write[String] and
  (JsPath \ "description").write[Option[String]] and
  (JsPath \ "contentType").write[String] and
  (JsPath \ "lastModify").write[Date] and
  (JsPath \ "size").write[Long] and
  (JsPath \ "link").write[String])
(f => (f.name, f.description, f.contentType, f.lastModify, f.size, routes.Document.downloadFromPermalink(f.uuid).absoluteURL(false)))

编辑wingedsubmariner的答案:

它不适用于范围内的请求:

  def documents(id: Long) = Action { implicit request =>
    Users.findById(id).map { user =>

      //get files from somewhere
      val files = XXX

      //it works if I put fileWrites here but I want a reusable function

      //error on this line : No Json deserializer found for type List[models.File]. Try to implement an implicit Writes or Format for this type.
      val json = Json.toJson(files)
      Ok(json)
    }.getOrElse(NotFound)
  }

  implicit def fileWrites(implicit request: RequestHeader) = new Writes[File] {
    def writes(file: File) = Json.obj(
      "name" -> file.name,
      "description" -> file.description,
      "contentType" -> file.contentType,
      "lastModify" -> file.lastModify,
      "size" -> file.size,
      "link" -> routes.Document.downloadFromPermalink(file.uuid).absoluteURL(false))
  }

【问题讨论】:

    标签: json scala playframework-2.0


    【解决方案1】:

    试试:

    implicit def fileWrites(implicit request: RequestHeader) = new Writes[File] {
      def writes(file: File) = Json.obj(
        "name" -> file.name,
        "description" -> file.description,
        "contentType" -> file.contentType,
        "lastModify" -> file.lastModify,
        "size" -> file.size,
        "link" -> routes.Document.downloadFromPermalink(file.uuid).absoluteURL(false)
      )
    }
    

    【讨论】:

    • 我尝试了这个,但在类型上出现错误:没有为类型 List[models.File] 找到 Json 反序列化器。尝试为此类型实现隐式写入或格式。
    • 如果您在范围内没有隐式RequestHeader,就会发生这种情况。错误报告不够聪明,无法告诉您它找到了filesWrites,但由于缺少RequestHeader 而没有使用它。
    猜你喜欢
    • 2015-05-02
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多