I use Play 2.2 json writes helper : http://www.playframework.com/documentation/2.2.x/ScalaJson
I want to write a json version of a File case class. Here is my writer :
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)
)
}
However this routes.Document.downloadFromPermalink(file.uuid).absoluteURL(false)
need an implicit request: RequestHeader
. If I put fileWrites definition in an action with the implicit request in scope, it works.
But I want to define fileWrites to be reusable between action. How can I write it so fileWrites take the implicit request as a parameter ?
Same question for this definition :
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)))
Edit for wingedsubmariner answer :
it's not working with a request in scope :
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))
}