【发布时间】:2015-05-17 05:01:25
【问题描述】:
我正在尝试实现basically the same thing that is discussed here,但在我的具体情况下,它不起作用。
目前我有一个函数可以验证来自我们服务器的 JSON 响应。问题是,它在方法中硬编码了 JSON 类型:
def fakeRequest[A: Writes](target: () => Call, requestObject: A): Any = {
route(FakeRequest(target()).withJsonBody(Json.toJson(requestObject))) match {
// ... stuff happens
Json.parse(contentAsString(response)).validate[GPInviteResponse]
^
注意硬编码的 GPInviteResponse 类型。
因此,要使其成为一个完全通用且可重用的方法,最好传入正在验证的类型。
我试过这个:
def fakeRequest[A: Writes, B](target: () => Call, requestObject: A, responseType: B): Any = {
route(FakeRequest(target()).withJsonBody(Json.toJson(requestObject))) match {
// ... stuff happens
Json.parse(contentAsString(response)).validate[B]
^
这几乎可以工作,但我得到了 No Json deserializer found for type B. 有道理,所以我将其更改为:
def fakeRequest[A: Writes, B: Reads](target: () => Call, requestObject: A, responseType: B): Any = {
但是,现在我得到了No Json deserializer found for type controllers.GPInviteResponse.type.,所以问题是:是否可以传递这样的类型(或者是否有其他魔法可以让它工作)?
有为该类型定义了一个反序列化器...我已经重读了六遍以确保没有错字:
case class GPInviteResponse(inviteSent: Boolean, URL: Option[String], error: Option[GPRequestError] = None) {
def this(error: GPRequestError) = this(false, None, Option(error))
}
object GPInviteResponse {
implicit val readsInviteResponse = Json.reads[GPInviteResponse]
implicit val writesInviteResponse = Json.writes[GPInviteResponse]
}
编辑
下面是一个演示问题的简化测试用例。目前,这不会编译(错误如下所示)。我想我理解为什么它不起作用(模糊地),但我不知道解决方案。我关于它为什么不起作用的理论:虽然提供的类型 GPInviteRequest 确实具有隐式读/写方法,但 Scala 无法建立实例 B 实际上是 GPInviteRequest 的连接,因此它得出结论 @987654331 @ 没有读/写。
case class GPInviteResponse(inviteSent: Boolean)
object GPInviteResponse {
implicit val readsInviteResponse = Json.reads[GPInviteResponse]
implicit val writesInviteResponse = Json.writes[GPInviteResponse]
}
class TestInviteServices extends PlaySpecification {
"try to validate a type" in {
tryToValidate(GPInviteRequest(true))
}
def tryToValidate[B: Reads, Writes](i: B) = {
val json = Json.toJson(i).toString
Json.parse(json).validate[B].isSuccess must beTrue
}
}
上述测试产生:
[错误] /Users/zbeckman/Projects/Glimpulse/Server-2/project/glimpulse-server/test/application/TestInviteServices.scala:46: 没有找到类型 B 的 Json 序列化程序。尝试实现隐式 写入或格式化此类型。 [错误] val json = Json.toJson(i).toString [错误] ^ [错误] /Users/zbeckman/Projects/Glimpulse/Server-2/project/glimpulse-server/test/application/TestInviteServices.scala:133: 找不到类型 controllers.GPInviteResponse.type 的 Json 反序列化器。 尝试为此类型实现隐式读取或格式。 [错误] fakeRequest(controllers.routes.GPInviteService.invite, 我, GPInviteResponse) 匹配 { [错误] ^
【问题讨论】:
-
你能举一个最小的例子来编译和展示问题吗?
标签: scala