![](/img/trans.png)
[英]Playframework 2.0.X scala - How to implement multiple json reads/writes for an object?
[英]Playframework 2.2.X scala - How can I use implicit variable in json's Writes
我使用Play 2.2 json编写助手: http : //www.playframework.com/documentation/2.2.x/ScalaJson
我想编写File case类的json版本。 这是我的作家:
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))
}
尝试:
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)
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.