玩! 2.4 - 隐式读取 Scala Json 与/通用类型
Play! 2.4 - Implicit Reads for ScalaJson w/ Generic Types
使用 Play 2.4 ScalaAWS。我定义了一个方法,该方法采用类型清单 T
并向外部 API 执行 GET
请求。问题是它无法编译,因为没有用于解析 JSON.
的隐式 Reads
代码如下:
def myGet[T](path: String)(implicit m: Manifest[T]): Future[Either[model.MyError,T]] = {
val url = MY_HOST+"/"+path
ws
.url(url)
.withHeaders(myHeaders: _*)
.get()
.map { response =>
try {
Right(response.json.as[T])
} catch {
// check if this response was an error
Left(response.json.as[model.MyError])
}
}
}
编译错误具体为:
Compilation error[No Json deserializer found for type T. Try to implement an implicit Reads or Format for this type.]
我不确定执行此操作的最简单方法。感谢您的帮助。
编辑
我也试过 (implicit m: Manifest[T], reads: Reads[T])
但没有成功。
事实证明,使用 (implicit m: Manifest[T], readsT: Reads[T])
并将 Reads
作为隐式参数是执行此操作的正确方法。我不得不 运行 sbt clean
因为某些东西在增量编译器中缓存不当。
现在可以正常使用了。
使用 Play 2.4 ScalaAWS。我定义了一个方法,该方法采用类型清单 T
并向外部 API 执行 GET
请求。问题是它无法编译,因为没有用于解析 JSON.
Reads
代码如下:
def myGet[T](path: String)(implicit m: Manifest[T]): Future[Either[model.MyError,T]] = {
val url = MY_HOST+"/"+path
ws
.url(url)
.withHeaders(myHeaders: _*)
.get()
.map { response =>
try {
Right(response.json.as[T])
} catch {
// check if this response was an error
Left(response.json.as[model.MyError])
}
}
}
编译错误具体为:
Compilation error[No Json deserializer found for type T. Try to implement an implicit Reads or Format for this type.]
我不确定执行此操作的最简单方法。感谢您的帮助。
编辑
我也试过 (implicit m: Manifest[T], reads: Reads[T])
但没有成功。
事实证明,使用 (implicit m: Manifest[T], readsT: Reads[T])
并将 Reads
作为隐式参数是执行此操作的正确方法。我不得不 运行 sbt clean
因为某些东西在增量编译器中缓存不当。
现在可以正常使用了。