我有以下类
case class PaginatedSearchResult[T : RootJsonFormat](pages: Option[Page], objects: Option[Seq[T]])
object PaginatedSearchResult extends DefaultJsonProtocol {
implicit val format = jsonFormat2(PaginatedSearchResult.apply)
}
我正试图把它分解成这样:
Unmarshal(response.entity).to[PaginatedSearchResult[T]]
这是我得到的错误
Error:(15, 59) could not find implicit value for evidence parameter of type spray.json.RootJsonFormat[T]
implicit val format = jsonFormat2(PaginatedSearchResult.apply)
我正试图弄清楚如何正确地将其分解。任何帮助都将不胜感激,谢谢。
有两个问题:
定义jsonFormat2(PaginatedSearchResult.apply)
时,缺少类型为RootJsonFormat[T]
的隐式值,因为它是构造函数/apply方法中所必需的。编译器不可能知道任何T
的情况,并给您错误
Error:(15, 59) could not find implicit value for evidence parameter of type spray.json.RootJsonFormat[T]
您可以通过将格式定义为def
来修复它
implicit def format[T: RootJsonFormat] = jsonFormat2(PaginatedSearchResult.apply)
第二个问题是你需要使用格式的地方
Unmarshal(response.entity).to[PaginatedSearchResult[T]]
在这种情况下,您必须使用具体的T
或在隐式作用域中使用RootJsonFormat[T]
。
你可以做这个
def unmarshal[T: RootJsonFormat] = {
Unmarshal(response.entity).to[PaginatedSearchResult[T]]
}
例如,如果您的类型为User
,请将其用作unmarshal[User]
。
我用以下代码修复了这个问题:
case class PaginatedSearchResult[T : JsonFormat](pages: Option[Page], objects: Option[Seq[T]])
object PaginatedSearchResult extends DefaultJsonProtocol {
implicit def format[T : JsonFormat]: RootJsonFormat[PaginatedSearchResult[T]] = jsonFormat2(PaginatedSearchResult.apply[T])
}