【发布时间】:2013-06-21 07:16:32
【问题描述】:
我已经被这个特殊问题困扰了大约一个星期,我想我将把这个问题写在这里作为一个问题来清理我的想法并获得一些指导。
所以我有一个具有java.sql.Timestamp 字段的案例类:
case class Request(id: Option[Int], requestDate: Timestamp)
我想把它转换成JsObject
val q = Query(Requests).list // This is Slick, a database access lib for Scala
printList(q)
Ok(Json.toJson(q)) // and this is where I run into trouble
“没有找到类型 List[models.Request] 的 Json 反序列化器。尝试为此类型实现隐式写入或格式。”好吧,这是有道理的。
所以按照Play documentation here,我尝试写一个Format...
implicit val requestFormat = Json.format[Request] // need Timestamp deserializer
implicit val timestampFormat = (
(__ \ "time").format[Long] // error 1
)(Timestamp.apply, unlift(Timestamp.unapply)) // error 2
错误 1
Description Resource Path Location Type overloaded method value format with alternatives:
(w: play.api.libs.json.Writes[Long])(implicit r: play.api.libs.json.Reads[Long])play.api.libs.json.OFormat[Long]
<and>
(r: play.api.libs.json.Reads[Long])(implicit w: play.api.libs.json.Writes[Long])play.api.libs.json.OFormat[Long]
<and>
(implicit f: play.api.libs.json.Format[Long])play.api.libs.json.OFormat[Long]
cannot be applied to (<error>, <error>)
显然像这样导入(请参阅documentation“ctrl+F 导入”)让我陷入困境:
import play.api.libs.json._ // so I change this to import only Format and fine
import play.api.libs.functional.syntax._
import play.api.libs.json.Json
import play.api.libs.json.Json._
现在重载错误消失了,我遇到了更多问题:not found: value __ 我已经导入了.../functional.syntax._,就像它在文档中所说的那样! This guy 遇到了同样的问题,但导入为他解决了这个问题!所以为什么?!我认为这可能只是 Eclipse 的问题并尝试play run 无论如何......没有任何改变。美好的。编译器永远是对的。
导入play.api.lib.json.JsPath,把__改成JsPath,还有wallah:
错误 2
value apply is not a member of object java.sql.Timestampvalue unapply is not a member of object java.sql.Timestamp
我还尝试更改策略并为此编写一个写入而不是格式,没有花哨的新组合器 (__) 功能,遵循original blog post the official docs are based on/copy-pasted from:
// I change the imports above to use Writes instead of Format
implicit val timestampFormat = new Writes[Timestamp]( // ERROR 3
def writes(t: Timestamp): JsValue = { // ERROR 4 def is underlined
Json.obj(
/* Returns the number of milliseconds since
January 1, 1970, 00:00:00 GMT represented by this Timestamp object. */
"time" -> t.getTime()
)
}
)
错误 3:trait Writes is abstract, cannot be instantiated
错误 4:illegal start of simple expression
在这一点上,我已经不知所措了,所以我只是回到我的心理堆栈的其余部分,并从我的第一段代码报告
我非常感谢任何能让我摆脱编码痛苦的人
【问题讨论】:
标签: java scala playframework playframework-2.0