我正在使用Akka HTTP(在Scala中)开发REST服务。我想要一个传递给http get请求的参数转换为ZonedDateTime类型。如果我尝试使用String或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
}
}
答案 0 :(得分:5)
由于struct scoped_locale_global {
scoped_locale_global(const std::locale& loc)
: m_prev_loc(std::locale::global(loc))
{
}
~scoped_locale_global()
{
std::locale::global(m_prev_loc);
}
std::locale m_prev_loc;
};
本身不是由Akka-HTTP编组的,因此您需要为ZonedDateTime
指令提供自定义的unmarshaller。
此功能在文档here中简要描述。
您可以使用parameters
从函数创建unmarshaller,例如
Unmarshaller.strict
此示例假定您的参数以ISO格式提供。如果不是,您需要修改解组功能。
然后,您可以使用unmarshaller将其传递给parameters指令:
val stringToZonedDateTime = Unmarshaller.strict[String, ZonedDateTime](ZonedDateTime.parse)