Scala Akka HTTP 强制参数为 java.time.ZonedDateTime



我正在使用Akka HTTP(在Scala中(开发REST服务。我希望将传递给 http get 请求的参数转换为 ZonedDateTime 类型。如果我尝试使用字符串或 Int 但因 ZonedDateTime 类型而失败,则代码工作正常。代码如下所示:

parameters('testparam.as[ZonedDateTime])

这是我看到的错误:

Error:(23, 35) type mismatch;
found   : akka.http.scaladsl.common.NameReceptacle[java.time.ZonedDateTime]
required: akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet
parameters('testparam.as[ZonedDateTime]){

如果我向列表中添加多个参数,则会出现不同的错误:

Error:(23, 21) too many arguments for method parameters: (pdm: akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet)pdm.Out
parameters('testparam.as[ZonedDateTime], 'testp2){

当我 http://doc.akka.io/japi/akka-stream-and-http-experimental/2.0/akka/http/scaladsl/server/directives/ParameterDirectives.html 研究问题时,我在文档中发现了这个问题,我尝试了添加import akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet和使用 Scala 2.11 的解决方法,但问题仍然存在。

有人可以解释一下我做错了什么以及为什么 ZonedDateTime 类型不起作用?提前感谢!

这是一个代码片段,应该重现我看到的问题

import java.time.ZonedDateTime
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import scala.io.StdIn

object WebServer {
def main(args: Array[String]) {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
// needed for the future flatMap/onComplete in the end
implicit val executionContext = system.dispatcher
val route =
path("hello") {
get {
parameters('testparam.as[ZonedDateTime]){
(testparam) =>
complete(testparam.toString)
}
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
}

由于ZonedDateTime不是由 Akka-HTTP 原生解组的,因此您需要为parameters指令提供自定义解组器。

此处的文档简要介绍了此功能。

您的解组器可以使用Unmarshaller.strict从函数创建,例如

val stringToZonedDateTime = Unmarshaller.strict[String, ZonedDateTime](ZonedDateTime.parse)

此示例假定您的参数以 ISO 格式提供。如果不是,则需要修改解组功能。

然后,您可以使用解组器将其传递给参数指令:

parameters('testparam.as(stringToZonedDateTime)){ testparam =>
complete(testparam.toString)
}

相关内容

最新更新